<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\ArtworkStatsService;
use Illuminate\Console\Command;

/**
 * Drain the Redis artwork-stat delta queue into MySQL.
 *
 * The ArtworkStatsService::incrementViews/Downloads methods push compressed
 * delta payloads to a Redis list (`artwork_stats:deltas`) when Redis is
 * available. This command drains that queue by applying each delta to the
 * artwork_stats table via applyDelta().
 *
 * Designed to run every 5 minutes so counters stay reasonably fresh while
 * keeping MySQL write pressure low. If Redis is unavailable the command exits
 * immediately without error — the service already fell back to direct DB
 * writes in that case.
 *
 * Usage:
 *   php artisan skinbase:flush-redis-stats
 *   php artisan skinbase:flush-redis-stats --max=500
 */
class FlushRedisStatsCommand extends Command
{
    protected $signature   = 'skinbase:flush-redis-stats {--max=1000 : Maximum deltas to process per run}';
    protected $description = 'Drain Redis artwork stat delta queue into MySQL';

    public function handle(ArtworkStatsService $service): int
    {
        $max = (int) $this->option('max');

        $processed = $service->processPendingFromRedis($max);

        if ($this->getOutput()->isVerbose()) {
            $this->info("Processed {$processed} artwork-stat delta(s) from Redis.");
        }

        return self::SUCCESS;
    }
}
