<?php

namespace App\Console\Commands;

use App\Models\Anime;
use App\Services\JikanService;
use Illuminate\Console\Command;

class FetchMalIds extends Command
{
    protected $signature   = 'animexe:fetch-mal-ids {--force : Overwrite existing MAL IDs}';
    protected $description = 'Auto-fetch MAL IDs for all animes and fill season mal_id chain via Jikan API';

    public function handle(): int
    {
        $jikan  = new JikanService();
        $query  = Anime::query();

        if (!$this->option('force')) {
            $query->whereNull('mal_id');
        }

        $animes = $query->get();
        $this->info("Processing {$animes->count()} anime(s)…");
        $bar = $this->output->createProgressBar($animes->count());
        $bar->start();

        $found = 0;
        foreach ($animes as $anime) {
            try {
                if (!$anime->mal_id || $this->option('force')) {
                    $malId = $jikan->searchMalId($anime->title, $anime->title_en, $anime->title_jp, $anime->type);
                    if ($malId) {
                        $anime->update(['mal_id' => $malId]);
                        $found++;
                    }
                    usleep(400_000); // rate limit
                }

                // Fill season chain
                if ($anime->mal_id) {
                    $chain = $jikan->fetchSeasonMalIds($anime->mal_id);
                    foreach ($anime->seasons()->orderBy('season_number')->get() as $i => $season) {
                        if (!$season->mal_id && isset($chain[$i])) {
                            $season->update(['mal_id' => $chain[$i]]);
                        }
                    }
                }
            } catch (\Throwable $e) {
                $this->newLine();
                $this->warn("  ⚠ [{$anime->title}]: {$e->getMessage()}");
            }

            $bar->advance();
        }

        $bar->finish();
        $this->newLine();
        $this->info("Done. {$found} new MAL ID(s) fetched.");
        return 0;
    }
}
