<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class EnsureMfaIsComplete
{
    public function handle(Request $request, Closure $next): Response
    {
        $guard = BuilderAuth::guard();
        $user = $request->user($guard);

        // Not authenticated — BuilderAuth handles this
        if (! $user) {
            return $next($request);
        }

        // MFA enforcement is optional; skip if disabled
        if (! (bool) config('builder.auth.require_mfa', false)) {
            return $next($request);
        }

        // Exempt routes: MFA challenge, account page, and mfa setup endpoints
        if ($request->routeIs('builder.mfa.*', 'builder.account.show', 'builder.account.mfa.*')) {
            return $next($request);
        }

        // MFA not yet set up → force setup on account page
        if ($user->getAttribute('two_factor_confirmed_at') === null) {
            return to_route('builder.account.show');
        }

        // MFA set up but not verified in this session → challenge
        if ($request->session()->get('mfa_verified') !== true) {
            return to_route('builder.mfa.challenge');
        }

        return $next($request);
    }
}
