<?php

namespace App\Http\Middleware;

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

/**
 * Gate every authenticated page behind a confirmed 2FA challenge for the
 * current session once the account has 2FA configured, and force staff
 * accounts (any role beyond the default "player") to set 2FA up before
 * they can reach anything — this is what actually enforces the "2FA for
 * admin roles" requirement, rather than leaving it optional everywhere.
 */
class EnsureTwoFactorIsConfirmed
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user) {
            return $next($request);
        }

        $requires2fa = $user->two_factor_secret !== null
            || $user->hasAnyRole(['superadmin', 'admin', 'moderator']);

        $routeName = $request->route()?->getName();
        $exempt = in_array($routeName, [
            'two-factor.challenge',
            'two-factor.setup',
            'two-factor.confirm',
            'logout',
        ], true);

        if ($exempt) {
            return $next($request);
        }

        if ($requires2fa && $user->two_factor_confirmed_at === null) {
            return redirect()->route('two-factor.setup')
                ->with('error', 'Two-factor authentication is required for your account. Please set it up to continue.');
        }

        if ($user->two_factor_confirmed_at !== null && ! session('google2fa_authenticated')) {
            return redirect()->route('two-factor.challenge');
        }

        return $next($request);
    }
}
