<?php

namespace Daylight\Core\Http\Middleware;

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

class EnsureTwoFactorAuthenticated
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! auth()->check()) {
            return $next($request);
        }

        if ($request->session()->has('impersonate')) {
            return $next($request);
        }

        $user = $request->user();

        if (! method_exists($user, 'hasTwoFactorEnabled') || ! $user->hasTwoFactorEnabled()) {
            return $next($request);
        }

        if ($request->session()->get('two_factor_authenticated') === true) {
            return $next($request);
        }

        if ($request->routeIs('*two-factor.challenge')) {
            return $next($request);
        }

        return redirect(translatedRoute('two-factor.challenge'));
    }
}
