<?php

namespace App\Http\Responses;

use App\Support\MaintenanceMode;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
use Symfony\Component\HttpFoundation\Response;

class TwoFactorLoginResponse implements TwoFactorLoginResponseContract
{
    public function toResponse($request): Response
    {
        $user = $request->user();

        if (MaintenanceMode::enabled() && !MaintenanceMode::allowsUser($user)) {
            Auth::guard()->logout();

            if ($request->hasSession()) {
                $request->session()->invalidate();
                $request->session()->regenerateToken();
            }

            return redirect()
                ->route('login')
                ->withErrors([
                    'email' => 'La plataforma está en mantenimiento. Solo administradores pueden iniciar sesión.',
                ]);
        }

        if (MaintenanceMode::enabled() && $user !== null && $user->is_admin) {
            return redirect()->intended(route('admin.home'));
        }

        return redirect()->intended(config('fortify.home'));
    }
}
