<?php

namespace apexl\Io\modules\user\services;

use apexl\Io\includes\System;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use Deprecated;

final class Permissions
{
    /**
     * Registry keyed `Enum::CASE`. Initialised so a read before the first
     * registerPermission() call is an empty map, not an uninitialised-property Error.
     *
     * @var array<string,RegisteredPermission>
     * @noinspection PhpGetterAndSetterCanBeReplacedWithPropertyHooksInspection
     * @Todo Replace array with collection and use get hook
     */
    public array $permissions = [];

    #[Deprecated]
    public static function getInstance(): Permissions
    {
        return System::getRegisteredService(Permissions::class);
    }

    public function registerPermission(PermissionInterface $permission, string $friendlyName, string $group = 'General'): void
    {
        $this->permissions[$this->toKey($permission)] = new RegisteredPermission($permission, $friendlyName, $group);
    }

    private function toKey(PermissionInterface $permission): string
    {
        return sprintf('%s::%s', $permission::class, $permission->name);
    }

    /** The registered enum case, or null when nothing is registered under that key. */
    public function getPermission(string|PermissionInterface $permission): ?PermissionInterface
    {
        return $this->getRegistration($permission)?->permission;
    }

    /** The registry entry (enum case + friendly name + group) behind a permission or key. */
    public function getRegistration(string|PermissionInterface $permission): ?RegisteredPermission
    {
        $key = $permission instanceof PermissionInterface ? $this->toKey($permission) : $permission;

        return $this->permissions[$key] ?? null;
    }

    /** @return array<string,RegisteredPermission> */
    public function getPermissions(): array
    {
        return $this->permissions;
    }
}
