<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Maps legacy artwork to the legacy episode it related to.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $artworks = Artwork::whereNotNull('legacy_id')->get();
        foreach ($artworks as $artwork) {
            if ($artwork->id > 76200) {
                $legacyDetailResponse = $this->getArtworkInfoFromApi($artwork->legacy_id);
                $response = $legacyDetailResponse->object();
                if ($response->artwork->episode_id) {
                    $episode = Episode::where('legacy_id', $response->artwork->episode_id)->first();
                    if ($episode) {
                        $artwork->episode_id = $episode->id;
                        $this->line('Artwork ID ' . $artwork->id . ' is mapped to Episode ID ' . $episode->id);
                        if ($artwork->isDirty()) {
                            $this->line('This is a new mapping.');
                            $artwork->save();
                        }
                    }
                }
            }
        }
    }

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