<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Operator;

use apexl\Io\operators\entityDatabaseOperator;
use apexl\Vault\Vault;

/**
 * Operators-pattern access to `permissions__roles` (enum-permission
 * grants keyed by role id; stored as PHP-`serialize()`d values).
 *
 * Extracted from RolePermissionManagerService so query construction
 * lives in one place. The manager keeps its public API + exception
 * wrapping; this operator owns the SQL.
 */
class RolePermissionOperator extends entityDatabaseOperator
{
    public const string TABLE = 'permissions__roles';

    public function __construct(Vault $vault)
    {
        parent::__construct(self::TABLE, 'role');
        $this->vault = $vault;
    }

    /**
     * Raw query rows ({permission: <serialised>}) for a role, in the
     * shape the permissionCollection factory expects (->fetchAll()).
     */
    public function listForRole(int $roleId): array
    {
        return $this->vault->select(self::TABLE)
            ->fields('permission')
            ->where('role', $roleId)
            ->execute()
            ->fetchAll();
    }

    public function insertForRole(int $roleId, string $serialisedPermission): void
    {
        $this->vault->insert(self::TABLE)
            ->fields([
                'role'       => $roleId,
                'permission' => $serialisedPermission,
            ])
            ->execute();
    }

    public function deleteForRole(int $roleId, string $serialisedPermission): void
    {
        $this->vault->delete(self::TABLE)
            ->where('role', $roleId)
            ->where('permission', $serialisedPermission)
            ->execute();
    }
}
