<?php

namespace App\Http\Middleware;

use App\Domain\License\Services\LicenseManager;
use App\Domain\Notifications\Models\PanelNotification;
use App\Domain\Reseller\Services\ResellerBrandingService;
use App\Domain\SystemInfo\Services\SystemInfoService;
use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that is loaded on the first page visit.
     */
    protected $rootView = 'app';

    /**
     * Determine the current asset version.
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        $user = $request->user();

        return [
            ...parent::share($request),
            'csrf_token' => csrf_token(),
            // Environment string ('local', 'staging', 'production') — UI'da Mock/dev rozetlerini gizlemek için.
            'env' => app()->environment(),
            'auth' => [
                'user' => $user ? [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'roles' => $user->getRoleNames()->all(),
                    'is_admin' => $user->hasRole('admin'),
                    'two_factor_enabled' => $user->two_factor_secret !== null,
                ] : null,
            ],
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'warning' => fn () => $request->session()->get('warning'),
            ],
            'notifications' => fn () => $user ? [
                'unread_count' => PanelNotification::query()
                    ->where('user_id', $user->id)
                    ->whereNull('read_at')
                    ->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
                    ->count(),
            ] : ['unread_count' => 0],
            'impersonation' => fn () => $request->session()->has('viewing_account_id') ? [
                'active' => true,
                'admin_name' => $request->session()->get('impersonator_name'),
                'account_id' => $request->session()->get('viewing_account_id'),
                'account_username' => $request->session()->get('viewing_account_username'),
                // Admin için: tüm hesapları (en fazla 50) — hızlı switcher dropdown'ı
                'available_accounts' => $user?->hasRole('admin')
                    ? \App\Domain\Account\Models\Account::query()
                        ->select('id', 'username', 'status')
                        ->orderBy('username')
                        ->limit(50)
                        ->get()
                        ->toArray()
                    : [],
            ] : ['active' => false],
            // Reseller branding — iki kaynak:
            //   1. Custom domain'den gelen request (DetectResellerBranding middleware
            //      ONOX_RESELLER_ID env'inden bayi tespit etti) — bu durumda kullanıcı
            //      role'ü ne olursa olsun panel branding'i bayinin markasına geçirilir
            //   2. Kullanıcı reseller role'ünde — kendi panel görünümü her zaman branded
            'reseller_branding' => fn () => $request->attributes->get('reseller_branding')
                ?? ($user?->hasRole('reseller')
                    ? app(ResellerBrandingService::class)->getBranding($user)
                    : null),
            // PWA / AI globals
            'vapid_public_key' => config('services.web_push.public'),
            'ai_enabled' => (bool) config('services.ai_assistant.enabled'),
            // System info — topbar live stats (5 saniye cache'li, sadece admin için)
            'system_info' => fn () => $user?->hasRole('admin')
                ? app(SystemInfoService::class)->all()
                : null,
            // i18n — locale for vue-i18n bootstrap
            'locale' => fn () => $request->user()?->locale
                ?? session('locale', config('app.locale', 'tr')),
            'available_locales' => [
                ['code' => 'tr', 'name' => 'Türkçe', 'flag' => '🇹🇷'],
                ['code' => 'en', 'name' => 'English', 'flag' => '🇬🇧'],
            ],
            // Phase 5 — Onboarding / tour state (cached 5 min per user)
            'onboarding' => fn () => $user
                ? \Cache::remember("onboarding:{$user->id}", 300, static function () use ($user): array {
                    $row = \DB::table('user_onboarding')->where('user_id', $user->id)->first();

                    return [
                        'completed_tours' => $row ? (json_decode($row->completed_tours, true) ?? []) : [],
                        'completed_initial_setup' => (bool) ($row?->completed_initial_setup ?? false),
                    ];
                })
                : null,
            // Phase 5 — License info (lazy — only resolved when accessed by page)
            // L2 refactor: JWT cache backed — tier/expires_at JWT claim'lerinden, in_grace_period drop.
            // Adım 4: expires_soon + days_until_expiry — UI banner için.
            'license' => fn () => app()->bound(LicenseManager::class)
                ? (static function (LicenseManager $mgr): array {
                    $expires = $mgr->expiresAt();
                    $days = $mgr->daysUntilExpiry();

                    return [
                        'tier' => $mgr->tier(),
                        'expires_at' => $expires?->toIso8601String(),
                        'is_valid' => $mgr->isValid(),
                        'in_grace_period' => false,  // L2 — JWT exp tek truth source, grace period dropped
                        'days_until_expiry' => $days,
                        'expires_soon' => $mgr->expiresSoon(14),
                        'is_expired' => $days !== null && $days < 0,
                    ];
                })(app(LicenseManager::class))
                : null,
        ];
    }
}
