<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Operator;

use apexl\Io\modules\user\entities\RefreshToken;
use apexl\Io\operators\entityDatabaseOperator;
use apexl\Vault\enums\WhereCondition;
use apexl\Vault\Vault;

/**
 * Operators-pattern access to `refresh_tokens` for the queries the entity
 * layer can't express (bulk housekeeping).
 */
class RefreshTokenOperator extends entityDatabaseOperator
{
    public function __construct(Vault $vault)
    {
        parent::__construct(RefreshToken::TABLE, RefreshToken::PRIMARY_KEY);
        $this->vault = $vault;
    }

    /**
     * How many rows expired before the given unix timestamp.
     */
    public function countExpiredBefore(int $timestamp): int
    {
        $result = $this->vault->select(RefreshToken::TABLE)
            ->fields(sprintf('count(%s) AS count', RefreshToken::PRIMARY_KEY))
            ->where('expiry', $timestamp, WhereCondition::LESS_THAN)
            ->execute()
            ->fetchAssoc();

        return (int) ($result['count'] ?? 0);
    }

    /**
     * Remove every row that expired before the given unix timestamp.
     */
    public function deleteExpiredBefore(int $timestamp): void
    {
        $this->vault->delete(RefreshToken::TABLE)
            ->where('expiry', $timestamp, WhereCondition::LESS_THAN)
            ->execute();
    }
}
