<?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\Vault\Vault;
use app\module\newtonsTrailers\Interface\PermissionInterface;

final readonly class rolePermissionManagerService
{
    const TABLE__PERMISSIONS_ROLES = 'permissions__roles';

    public function __construct(private roleEntity $role, private Vault $vault)
    {
    }


    public function can(PermissionInterface|string $permission): bool
    {
        if ($permission instanceof PermissionInterface) {
            $permission = serialize($permission);
        }

        if ($this->permissions()->contains($permission)) {
            return true;
        }

        return false;
    }

    public function permissions(): permissionCollection
    {
        $roleId = $this->role->id;

        return permissionCollection::createFromQueryResult(
            $this->vault->select(self::TABLE__PERMISSIONS_ROLES)
                ->fields('permission')
                ->where('role', $roleId)
                ->execute()
                ->fetchAll()
        );
    }

    public function add(PermissionInterface $permission): void
    {
        $roleId = $this->role->id;

        $this->vault->insert(self::TABLE__PERMISSIONS_ROLES)
            ->fields([
                'role' => $roleId,
                'permission' => serialize($permission),
            ])->execute();
    }

    public function remove(PermissionInterface $permission): void
    {
        $roleId = $this->role->id;

        $this->vault->delete(self::TABLE__PERMISSIONS_ROLES)
            ->where('role', $roleId)
            ->where('permission', serialize($permission))
            ->execute();
    }
}
