<?php

namespace App\Http\Middleware;

use App\Support\TenantPermissionCatalog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

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

        $routePermissions = TenantPermissionCatalog::permissionsForRoute($request->route()?->getName());
        $hasRoutePermission = collect($routePermissions)
            ->contains(fn (string $permission): bool => $user->hasPermission($permission));

        if (! in_array($user->role, $roles, true) && ! $hasRoutePermission) {
            abort(403, 'You do not have permission to access this area.');
        }

        return $next($request);
    }
}
