<?php

declare(strict_types=1);

namespace ServerManager\Middleware;

use ServerManager\Core\Session;

class RoleMiddleware
{
    private string $requiredRole;

    public function __construct(string $requiredRole = 'admin')
    {
        $this->requiredRole = $requiredRole;
    }

    public function handle(): mixed
    {
        $userRole = Session::get('user_role');

        $roleHierarchy = [
            'super_admin' => 3,
            'admin' => 2,
            'operator' => 1,
        ];

        $requiredLevel = $roleHierarchy[$this->requiredRole] ?? 0;
        $userLevel = $roleHierarchy[$userRole] ?? 0;

        if ($userLevel < $requiredLevel) {
            if ($this->isApiRequest()) {
                http_response_code(403);
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Forbidden: insufficient permissions']);
                exit;
            }

            Session::setFlash('error', 'You do not have permission to access this area.');
            header('Location: /dashboard');
            exit;
        }

        return null;
    }

    private function isApiRequest(): bool
    {
        return str_starts_with($_SERVER['REQUEST_URI'] ?? '', '/api/') ||
               str_starts_with($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
    }

    public static function superAdmin(): self
    {
        return new self('super_admin');
    }

    public static function admin(): self
    {
        return new self('admin');
    }

    public static function operator(): self
    {
        return new self('operator');
    }
}
