<?php

namespace Modules\Vrc\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcUserSecurity;

/**
 * Enforces VRC step-up two-factor auth. Fail-open by design: it ONLY challenges a
 * user who has explicitly enabled 2FA (vrc_user_security.is_enabled) and hasn't
 * verified this session — so it can never lock out a user who didn't opt in. The
 * 2FA routes themselves are skipped to avoid a redirect loop.
 */
class VrcTwoFactor
{
    public function handle(Request $request, Closure $next)
    {
        $routeName = optional($request->route())->getName() ?? '';

        // Never gate the 2FA setup/challenge/verify endpoints.
        if (str_starts_with($routeName, 'vrc.security.2fa')) {
            return $next($request);
        }

        if (! auth()->check() || $request->session()->get('vrc_2fa_verified') === true) {
            return $next($request);
        }

        $businessId = (int) $request->session()->get('user.business_id');
        if (! $businessId) {
            return $next($request);
        }

        $enabled = VrcUserSecurity::where('business_id', $businessId)
            ->where('user_id', auth()->id())
            ->where('is_enabled', true)
            ->exists();

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

        if ($request->ajax() || $request->wantsJson()) {
            abort(423, 'Two-factor verification required.');
        }

        return redirect()->route('vrc.security.2fa.challenge');
    }
}
