<?php

namespace App\Console\Commands;

use App\Models\Airport;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

#[Signature('app:populate-airport-timezones')]
#[Description('Populate timezone data for all airports using lat/lng')]
class PopulateAirportTimezones extends Command
{
    /**
     * Execute the console command.
     */
    public function handle()
    {
        Airport::whereNull('timezone')->chunkById(100, function ($airports) {
            foreach ($airports as $airport) {
                $zoneName = null;
                $attempts = 0;

                while ($zoneName === null && $attempts < 3) {
                    $response = Http::withoutVerifying()
                        ->withOptions(['allow_redirects' => false])
                        ->get('http://vip.timezonedb.com/v2.1/get-time-zone', [
                            'key' => config('app.timezone_api_key'),
                            'format' => 'json',
                            'by' => 'position',
                            'lat' => $airport->latitude_deg,
                            'lng' => $airport->longitude_deg,
                        ]);

                    $zoneName = $response->json('zoneName');
                    $attempts++;

                    if ($zoneName === null) {
                        $this->warn("✗ {$airport->name} — attempt {$attempts} failed: " . $response->body());
                        sleep(5);
                    }
                }

                if ($zoneName) {
                    $airport->update(['timezone' => $zoneName]);
                    $this->info("✓ {$airport->name} — {$zoneName}");
                } else {
                    $this->warn("✗ {$airport->name} — giving up after {$attempts} attempts".$response->body());
                }
            }
        });

        $this->info('Done!');
    }
}
