<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\modules\user\collections\permissionCollection;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use apexl\Io\modules\user\Operator\RolePermissionOperator;
use apexl\Vault\Vault;

final readonly class RolePermissionManagerService
{
    public function __construct(private roleEntity $role, private Vault $vault) {}


    public function can(PermissionInterface|string $permission): bool
    {
        if ($this->permissions()->contains($permission)) {
            return true;
        }

        return false;
    }

    public function permissions(): permissionCollection
    {
        return permissionCollection::createFromQueryResult(
            $this->operator()->listForRole($this->role->id)
        );
    }

    public function add(PermissionInterface $permission): void
    {
        $this->operator()->insertForRole($this->role->id, serialize($permission));
    }

    public function remove(PermissionInterface $permission): void
    {
        $this->operator()->deleteForRole($this->role->id, serialize($permission));
    }

    private function operator(): RolePermissionOperator
    {
        return new RolePermissionOperator($this->vault);
    }
}
