<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Expiration;

use PrettyLinks\GroundLevel\Resque\Models\Job;
use RuntimeException;

/**
 * Resque job behind TrashSweeper — trashes one batch of date-expired
 * trash-action links and re-enqueues itself while full batches keep
 * making progress. Thin wrapper: all logic lives in TrashSweeper so it
 * can be tested without the worker.
 */
class TrashExpiredLinksJob extends Job
{
    /**
     * Trash one batch; re-enqueue while more remain.
     *
     * @return void
     *
     * @throws RuntimeException When the next batch cannot be queued, so the
     *                          worker retries instead of dropping the rest
     *                          of the sweep.
     */
    protected function perform(): void
    {
        $args = json_decode((string) $this->getAttribute('args'), true);
        if (!is_array($args)) {
            // Fail loud on a corrupt payload (matches ClearClicksJob) rather
            // than silently restarting the scan from id 0.
            throw new RuntimeException('TrashExpiredLinksJob received an invalid args payload.');
        }
        $afterId = (int) ($args['after_id'] ?? 0);

        $result = (new TrashSweeper())->sweepBatch($afterId);

        // Carry the keyset cursor forward so the next batch resumes past every
        // row this one examined (trashed or blocked) — never re-scanning them.
        if ($result['moreRemain'] && (new self())->enqueue(['after_id' => $result['lastId']]) === false) {
            throw new RuntimeException('TrashExpiredLinksJob could not enqueue the next batch.');
        }
    }
}
