<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Operator;

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

/**
 * Operators-pattern access to `users__roles` (role assignments keyed by
 * user id).
 *
 * Extracted from UserRoleManagerService. The manager keeps its public
 * API + PermissionException wrapping + the role-id resolution logic;
 * this operator owns the SQL only.
 */
class UserRoleOperator extends entityDatabaseOperator
{
    public const string TABLE = 'users__roles';

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

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

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

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

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