<?php

namespace App\Http\Middleware;

use App\Models\Setting;
use App\Services\CitizenshipService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class EnsureEmailIsVerified
{
    /**
     * Allowed routes for each verification step.
     * Users can access these routes even when verification is pending.
     */
    private const ALLOWED_ROUTES = [
        'email' => [
            'store.auth.verify-email',
            'store.auth.resend-email-verification',
            'store.auth.logout',
        ],
        'sms' => [
            'store.auth.verify-phone',
            'store.auth.send-phone-verification',
            'store.auth.logout',
        ],
        'citizenship' => [
            'store.auth.verify-citizenship',
            'store.auth.logout',
        ],
    ];

    /**
     * Handle an incoming request.
     * Checks verifications in order: email → sms → citizenship
     */
    public function handle(Request $request, Closure $next)
    {
        if (! Auth::guard('client')->check()) {
            return $next($request);
        }

        $client = Auth::guard('client')->user();
        $routeName = $request->route()?->getName();

        // 1. Email verification
        if (Setting::getValue('email_verification', true) && ! $client->email_verified_at) {
            if ($this->isAllowedRoute($routeName, 'email')) {
                return $next($request);
            }

            return $this->respond($request, 'store.auth_email_verification_required', 'store.auth.verify-email');
        }

        // 2. SMS verification
        if (Setting::getValue('sms_verification', false) && ! $client->phone_verified_at) {
            if ($this->isAllowedRoute($routeName, 'sms')) {
                return $next($request);
            }

            return $this->respond($request, 'store.auth_phone_verification_required', 'store.auth.verify-phone');
        }

        // 3. Citizenship verification (only if enabled AND client's country has settings)
        $citizenshipEnabled = Setting::getValue('citizenship_verification', false) || Setting::getValue('verification_enabled', false);
        if ($citizenshipEnabled && in_array($client->verification_status, ['unverified', 'pending', 'expired'], true)) {
            $countryCode = $client->country?->a2_iso;
            $hasCountrySettings = $countryCode
                ? \App\Models\CitizenshipCountrySetting::where('country_code', $countryCode)->exists()
                : false;

            if ($hasCountrySettings) {
                if ($this->isAllowedRoute($routeName, 'citizenship')) {
                    return $next($request);
                }

                return $this->respond($request, 'store.auth_citizenship_verification_required', 'store.auth.verify-citizenship');
            }
        }

        return $next($request);
    }

    private function isAllowedRoute(?string $routeName, string $step): bool
    {
        if (! $routeName) {
            return false;
        }

        // Allow all verification routes (user might be on email verify and complete it, then needs sms)
        $allAllowed = array_merge(
            self::ALLOWED_ROUTES['email'],
            self::ALLOWED_ROUTES['sms'],
            self::ALLOWED_ROUTES['citizenship']
        );

        return in_array($routeName, $allAllowed);
    }

    private function respond(Request $request, string $messageKey, string $route)
    {
        if ($request->expectsJson()) {
            return response()->json([
                'message' => __($messageKey),
                'redirect' => route($route),
            ], 403);
        }

        return redirect()->route($route)
            ->with('warning', __($messageKey));
    }
}
