<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{

    private array $countryCodes = [
        'Burma'                        => 'MM', // Myanmar
        'Ceylon'                       => 'LK', // Sri Lanka
        'congodr'                      => 'CD', // Congo, Dem. Republic
        'cotedivoire'                  => 'CI', // Côte d'Ivoire
        'dominicanrep'                 => 'DO', // Dominican Republic
        'Kenya, Uganda and Tanzania'   => 'KE', // East African Airways — headquartered in Nairobi
        'Korea, Republic of'           => 'KR', // South Korea
        'Malaysia / Singapore'         => 'MY', // Malaysia-Singapore Airlines predecessor
        'Rhodesia'                     => 'ZW', // Zimbabwe
        'Saudia Arabia'                => 'SA', // Typo for Saudi Arabia
        'St. Barthelemy'               => 'BL', // Saint Barthélemy
        'St. Martin'                   => 'MF', // Saint Martin (French side — change to SX for Dutch)
        'Tanzania, United Republic of' => 'TZ',
        'uae'                          => 'AE', // United Arab Emirates
        'United States of America'     => 'US',
        'West Samoa'                   => 'WS', // Samoa
    ];
    public function up(): void
    {
        // 1. Insert Lufthansa
        DB::table('airlines')->insert([
            'IATA_code'     => 'LH',
            'ICAO_code'     => 'DLH',
            'name'          => 'Lufthansa',
            'internal_name' => 'lufthansa',
            'country_code'  => 'DE',
            'country_name'  => 'Germany',
            'active'        => true,
            'logo'          => 'LH.png',
        ]);

        // 2. Add nullable country_id FK column
        Schema::table('airlines', function (Blueprint $table) {
            $table->foreignId('country_id')
                ->nullable()
                ->after('active')
                ->constrained('countries', 'id')
                ->onUpdate('cascade')
                ->onDelete('set null');
        });


        foreach ($this->countryCodes as $countryName => $isoCode) {
            DB::statement("
                UPDATE airlines a
                SET    country_id = c.id
                FROM   countries c
                WHERE  c.code          = :code
                  AND  a.country_name  = :name
                  AND  a.country_id   IS NULL
            ", [
                'code' => $isoCode,
                'name' => $countryName,
            ]);
        }

    }

    public function down(): void
    {
        // Remove the FK column
        Schema::table('airlines', function (Blueprint $table) {
            $table->dropConstrainedForeignId('country_id');
        });

        // Remove Lufthansa (identified by unique ICAO code)
        DB::table('airlines')->where('ICAO_code', 'DLH')->delete();
    }
};
