<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Jobs\IndexArtworkJob;
use App\Models\Artwork;
use Illuminate\Console\Command;

class ReindexRecentPublishedArtworksCommand extends Command
{
    protected $signature = 'artworks:search-reindex-recent
                            {--hours=72 : Reindex artworks published in the last N hours}
                            {--limit=1000 : Maximum artworks to process in this run}
                            {--id=* : Specific artwork IDs to reindex (overrides --hours window)}
                            {--dry-run : Show candidates without dispatching index jobs}';

    protected $description = 'Reindex recently published public artworks to recover missed search indexing.';

    public function handle(): int
    {
        $hours = max(1, (int) $this->option('hours'));
        $limit = max(1, (int) $this->option('limit'));
        $ids = array_values(array_unique(array_filter(array_map('intval', (array) $this->option('id')), static fn (int $id): bool => $id > 0)));
        $dryRun = (bool) $this->option('dry-run');

        $since = now()->subHours($hours);

        $query = Artwork::query()
            ->whereNull('deleted_at')
            ->where('is_public', true)
            ->where('is_approved', true)
            ->whereNotNull('published_at');

        if ($ids !== []) {
            $query->whereIn('id', $ids)->orderBy('id');
        } else {
            $query->where('published_at', '>=', $since)
                ->orderByDesc('published_at');
        }

        $candidates = $query->limit($limit)->get(['id', 'title', 'slug', 'published_at']);

        if ($candidates->isEmpty()) {
            if ($ids !== []) {
                $this->line('No matching published artworks found for the provided --id values.');
            } else {
                $this->line("No published artworks found in the last {$hours} hour(s).");
            }
            return self::SUCCESS;
        }

        if ($ids !== []) {
            $this->info('Found ' . $candidates->count() . ' target artwork(s) by --id.' . ($dryRun ? ' [DRY RUN]' : ''));
        } else {
            $this->info("Found {$candidates->count()} artwork(s) published in the last {$hours} hour(s)." . ($dryRun ? ' [DRY RUN]' : ''));
        }

        foreach ($candidates as $artwork) {
            if ($dryRun) {
                $this->line("  [dry-run] Would reindex #{$artwork->id} ({$artwork->slug})");
                continue;
            }

            IndexArtworkJob::dispatchSync((int) $artwork->id);
            $this->line("  Reindexed #{$artwork->id} ({$artwork->slug})");
        }

        if (! $dryRun) {
            $this->info('Done. Recent published artworks were reindexed.');
        }

        return self::SUCCESS;
    }
}
