<?php

declare(strict_types=1);

namespace App\Modules\Administration\Services;

use App\Modules\Administration\Repositories\AuthorizationRepository;

final class AuthorizationService
{
    public function __construct(
        private AuthorizationRepository $authorization
    ) {
    }

    public function isAdministrator(): bool
    {
        $userId = (int) (
            $_SESSION['user_id'] ?? 0
        );

        if ($userId < 1) {
            return false;
        }

        $roles = $this->authorization->userRoles(
            $userId
        );

        return in_array(
            'Administrator',
            $roles,
            true
        );
    }

    public function can(
        string $permission
    ): bool {
        if ($this->isAdministrator()) {
            return true;
        }

        $userId = (int) (
            $_SESSION['user_id'] ?? 0
        );

        if ($userId < 1) {
            return false;
        }

        $permissions =
            $this->authorization->userPermissions(
                $userId
            );

        return in_array(
            $permission,
            $permissions,
            true
        );
    }
}