<?php

namespace apexl\Io\modules\user\services;

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

final class Permissions
{
    /**
     * @var array<string,PermissionInterface>
     * @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)] = (object) [
            'name' => $friendlyName,
            'group' => $group,
        ];
    }

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

    public function getPermission(string|PermissionInterface $permission): ?PermissionInterface
    {
        if ($permission instanceof PermissionInterface) {
            $permission = $this->toKey($permission);
        }

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

    public function getPermissions(): array
    {
        return $this->permissions;
    }
}
