<?php

use App\Models\Airline;
use App\Models\Alliance;
use App\Models\User;
use App\Models\UserFlight;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('airlines', function (Blueprint $table) {
            $table->foreignId('merged_into_id')->nullable()->after('alliance_id')->constrained('airlines')->nullOnDelete();
        });

        $madagascarAirlines = Airline::where('internal_name', 'air-madagascar')->first();
        $madagascarAirlines->update(['internal_name' => 'madagascar-airlines']);

        $airMadagascar = Airline::create([
            'iata_code' => 'MD',
            'icao_code' => 'MDG',
            'name' => 'Air Madagascar',
            'internal_name' => 'air-madagascar',
            'active' => false,
            'logo' => 'MD.png',
            'country_id' => 140,
            'alliance_id' => null,
            'merged_into_id' => $madagascarAirlines->id,
        ]);

        UserFlight::where('airline_id', $madagascarAirlines->id)->first()->update(['airline_id' => $airMadagascar->id]);

        foreach(User::all() as $user) {
            $user->calculateAchievements();
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};
