<?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__users` (direct per-user
 * enum-permission grants; stored as PHP-`serialize()`d values).
 *
 * Extracted from UserPermissionManagerService. The manager keeps its
 * public API + PermissionException wrapping; this operator owns the SQL.
 */
class UserPermissionOperator extends entityDatabaseOperator
{
    public const string TABLE = 'permissions__users';

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

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

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

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

    public function clearForUser(int $userId): void
    {
        $this->vault->delete(self::TABLE)
            ->where('user', $userId)
            ->execute();
    }
}
