<?php

namespace App\Http\Middleware;

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

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

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

        $requiredPermissions = $permissions ?: TenantPermissionCatalog::permissionsForRoute($request->route()?->getName());

        if ($requiredPermissions === []) {
            return $next($request);
        }

        foreach ($requiredPermissions as $permission) {
            if ($user->hasPermission($permission)) {
                return $next($request);
            }
        }

        abort(403, 'Your role profile does not allow this action.');
    }
}
