<?php

namespace App\Http\Middleware;

use App\Support\AdminProjectPermissionRegistry;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminProjectAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $admin = Auth::guard('admin')->user();

        if (!$admin) {
            abort(403);
        }

        if ($admin->isSuperAdmin()) {
            return $next($request);
        }

        $routeName = $request->route()?->getName();

        if (AdminProjectPermissionRegistry::isAlwaysAllowedRoute($routeName)) {
            return $next($request);
        }

        if (AdminProjectPermissionRegistry::isRouteAllowedForProjects($routeName, $admin->assignedProjectPermissions(), $request)) {
            return $next($request);
        }

        abort(403, 'You do not have permission for this module.');
    }
}
