<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\Artwork;
use App\Models\Episode;

class MapSelectedLegacyArtworkToEpisode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'naart:map-selected';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Maps the correct artwork selected to the legacy episodes';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $episodes = Episode::all();
        foreach ($episodes as $episode) {
            $this->line('Checking episode ' . $episode->episode_number);
            $legacyEpisodeResponse = $this->getEpisodeFromApi($episode->episode_number);
            $response = $legacyEpisodeResponse->object();
            if ($response->episode->artwork_id && $response->episode->artwork_id + 0 > 0) {
                $selectedArtwork = Artwork::where('legacy_id', $response->episode->artwork_id)->first();
                if ($selectedArtwork) {
                    $episode->artwork_id = $selectedArtwork->id;
                    $this->line('Artwork ID ' . $selectedArtwork->id . ' marked as episode artwork for episode ' . $episode->episode_number);
                    if ($episode->isDirty()) {
                        $this->line('This is a new mapping.');
                        $episode->save();
                    }
                }
            }
        }
    }

    private function getEpisodeFromApi($episode_legacy_id) {
        $response = Http::timeout(180)
            ->get('https://noagendaartgenerator.com/episodeapi/' . $episode_legacy_id, 
                [
                    'p' => '7476',
                ]
            );
        return $response;
    }
}
