<?php

namespace App\Http\Middleware;

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

class EnsureAdminUser
{
    public function handle(Request $request, Closure $next, string ...$roles): Response|RedirectResponse
    {
        $user = $request->user();

        if (! $user) {
            return redirect()->route('login');
        }

        $allowedRoles = $roles !== []
            ? array_map(static fn (string $role): string => strtolower(trim($role)), $roles)
            : ['administrador'];

        if (! method_exists($user, 'hasAnyRole') || ! $user->hasAnyRole($allowedRoles)) {
            return redirect()
                ->route('dashboard')
                ->with('warning', 'No tiene permisos para acceder a esta seccion.');
        }

        return $next($request);
    }
}