<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use ImovelZapAi\SuperAdmin\Infrastructure\Persistence\Eloquent\PlatformOperatorModel;
use Symfony\Component\HttpFoundation\Response;

final class EnsurePlatformMfa
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! (bool) config('superadmin.mfa_required', false)) {
            return $next($request);
        }

        if ($request->routeIs('super-admin.mfa.*', 'super-admin.logout')) {
            return $next($request);
        }

        /** @var PlatformOperatorModel|null $operator */
        $operator = Auth::guard('platform')->user();
        if ($operator === null) {
            return $next($request);
        }

        if (! $request->session()->get('platform_mfa_passed')) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'MFA required.'], 403);
            }

            return redirect()->route('super-admin.mfa.challenge');
        }

        return $next($request);
    }
}
