<?php

namespace App\Http\Middleware;

use App\Models\Core\Language;
use App\Models\Core\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\File;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        // Check if we're in installation mode
        $isInstalling = str_starts_with($request->path(), 'install');

        // Base shared data
        $shared = [
            'flash' => [
                'success' => fn() => $request->session()->get('success'),
                'error' => fn() => $request->session()->get('error'),
            ],
            'locale' => App::getLocale(),
        ];

        // Only add database-dependent data if not installing
        if (!$isInstalling && env('APP_INSTALL', false)) {
            $shared = array_merge($shared, [
                'auth' => [
                    'user' => $request->user()
                        ? $request->user()->load(['currentWorkspace', 'workspaces'])
                        : null,
                ],

                'language' => function () {
                    try {
                        $locale = App::getLocale();
                        $code = session('country_code');
                        return Language::where('lang_code', $locale)
                            ->where('code', $code)
                            ->first();
                    } catch (\Throwable $e) {
                        return null;
                    }
                },

                'translations' => function () {
                    try {
                        $locale = App::getLocale();
                        $filePath = resource_path("lang/{$locale}/messages.php");
                        return File::exists($filePath) ? require $filePath : [];
                    } catch (\Throwable $e) {
                        return [];
                    }
                },

                'site_logo' => function () {
                    try {
                        $setting = Setting::with('file')
                            ->where('key', 'site_logo')
                            ->first();

                        if (!$setting) {
                            return asset('assets/images/default/site_logo/site_log.png');
                        }

                        $logoFile = $setting->file()?->where('type', 'site_logo')->first();

                        return $logoFile
                            ? asset(config("settings")['file_path']['site_logo']['path'] . '/' . $logoFile->name)
                            : asset('assets/images/default/site_logo/site_logo.png');

                    } catch (\Throwable $e) {
                        return asset('assets/images/default/site_logo/site_log.png');
                    }
                },

                'languageProp' => fn() => Language::active()->get(),

                'notifications' => function() use ($request) {
                    try {
                        if ($request->user()) {
                            return \App\Models\Notification::where('notificationable_type', 'App\Models\User')
                                ->where('notificationable_id', $request->user()->id)
                                ->latest()
                                ->limit(10)
                                ->get();
                        }
                        return collect([]);
                    } catch (\Throwable $e) {
                        return collect([]);
                    }
                },

                'unread_notifications_count' => function() use ($request) {
                    try {
                        if ($request->user()) {
                            return \App\Models\Notification::where('notificationable_type', 'App\Models\User')
                                ->where('notificationable_id', $request->user()->id)
                                ->where('is_read', '!=', 1)
                                ->count();
                        }
                        return 0;
                    } catch (\Throwable $e) {
                        return 0;
                    }
                },

                'site_settings' => fn() => Setting::all()->pluck('value', 'key'),
            ]);
        } else {
            // Provide defaults for installation
            $shared = array_merge($shared, [
                'auth' => ['user' => null],
                'language' => null,
                'translations' => [],
                'site_logo' => asset('assets/images/default/site_logo/site_logo.png'),
                'languageProp' => [],
                'notifications' => collect([]),
                'unread_notifications_count' => 0,
                'site_settings' => [],
            ]);
        }

        return array_merge(parent::share($request), $shared);
    }
}
