<?php

namespace App\Http\Middleware;

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

class AuthorizePanelRoute
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $routeName = (string) ($request->route()?->getName() ?? '');
        $permission = PermissionCatalog::permissionForRoute($routeName);

        if (!$user) {
            return $next($request);
        }

        if ($permission) {
            abort_unless($user->can($permission), 403);

            return $next($request);
        }

        if (
            (str_starts_with($routeName, 'admin.') || str_starts_with($routeName, 'owner.'))
            && !in_array($routeName, ['admin.', 'owner.'], true)
        ) {
            abort(403);
        }

        return $next($request);
    }
}
