<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\Auth;
use App\Core\Middleware;
use App\Core\Request;
use App\Core\Response;
use RuntimeException;

final class PermissionMiddleware implements Middleware
{
    public function __construct(private string $permission) {}

    public function handle(Request $request, callable $next): mixed
    {
        if (!Auth::check()) {
            return Response::redirect('/crm/public/login');
        }

        if (!Auth::hasPermission($this->permission)) {
            throw new RuntimeException('You do not have permission to access this page.', 403);
        }

        return $next();
    }
}
