<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\Auth;
use App\Core\MiddlewareInterface;
use App\Core\Rbac;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;

/**
 * PermissionMiddleware
 *
 * Usage in routes/web.php:
 *   $router->post('/leads', 'App\Controllers\LeadController@store',
 *       middleware: ['auth', 'permission:leads_customers.create']);
 *
 * Always register 'auth' before 'permission:*' on a route — this
 * middleware assumes a user is already authenticated (Auth::id() is
 * not null) and only checks WHAT they're allowed to do, not WHETHER
 * they're logged in at all.
 */
final class PermissionMiddleware implements MiddlewareInterface
{
    public function __construct(private readonly ?string $permissionSlug)
    {
    }

    public function handle(Request $request, callable $next): Response
    {
        $userId = Auth::id();

        if ($this->permissionSlug === null || $userId === null || !Rbac::userCan($userId, $this->permissionSlug)) {
            if ($request->isAjax() || $request->isJson()) {
                return AjaxResponse::forbidden();
            }

            return Response::html('403 Forbidden — you do not have permission to view this page.', 403);
        }

        return $next($request);
    }
}
