<?php

declare(strict_types=1);

namespace App\Console\Commands;

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

/**
 * php artisan skinbase:recalculate-trending [--period=1h|24h|7d] [--chunk=1000] [--skip-index]
 */
class RecalculateTrendingCommand extends Command
{
    protected $signature = 'skinbase:recalculate-trending
                            {--period=7d   : Period to recalculate (1h, 24h or 7d). Use "all" to run all three.}
                            {--chunk=1000  : DB chunk size}
                            {--skip-index  : Skip dispatching Meilisearch re-index jobs}';

    protected $description = 'Recalculate trending scores for artworks and sync to Meilisearch';

    public function __construct(private readonly TrendingService $trending)
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $period    = (string)  $this->option('period');
        $chunkSize = (int)     $this->option('chunk');
        $skipIndex = (bool)    $this->option('skip-index');

        $periods = $period === 'all' ? ['1h', '24h', '7d'] : [$period];

        foreach ($periods as $p) {
            if (! in_array($p, ['1h', '24h', '7d'], true)) {
                $this->error("Invalid period '{$p}'. Use 1h, 24h, 7d, or all.");
                return self::FAILURE;
            }

            $this->info("Recalculating trending ({$p}) …");
            $start   = microtime(true);
            $updated = $this->trending->recalculate($p, $chunkSize);
            $elapsed = round(microtime(true) - $start, 2);

            $this->info("  ✓ {$updated} artworks updated in {$elapsed}s");

            if (! $skipIndex) {
                $this->info("  Dispatching Meilisearch index jobs …");
                $this->trending->syncToSearchIndex($p);
                $this->info("  ✓ Index jobs dispatched");
            }
        }

        return self::SUCCESS;
    }
}
