<?php

namespace App\Actions\Fortify;

use App\Models\User;
use App\Support\MaintenanceMode;
use Closure;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;

class EnsureAdminLoginDuringMaintenance
{
    /**
     * @param  mixed  $request
     */
    public function handle($request, Closure $next)
    {
        if (! MaintenanceMode::enabled()) {
            return $next($request);
        }

        $email = (string) $request->input(Fortify::username(), '');

        if ($email === '') {
            return $next($request);
        }

        $user = User::query()
            ->where(Fortify::username(), $email)
            ->first();

        if ($user !== null && !MaintenanceMode::allowsUser($user)) {
            throw ValidationException::withMessages([
                Fortify::username() => [
                    'La plataforma está en mantenimiento. Solo administradores pueden iniciar sesión.',
                ],
            ]);
        }

        return $next($request);
    }
}
