<?php

declare(strict_types=1);

namespace Apexl\Io\User\Services;

use Apexl\Io\User\Collections\PermissionCollection;
use Apexl\Io\User\Entities\RoleEntity;
use Apexl\Io\User\Interfaces\PermissionInterface;
use Apexl\Io\User\Operators\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);
    }
}
