<?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
{
    public function up(): void
    {
        // Add the FK column first, nullable so we can populate it before constraining
        Schema::table('regions', function (Blueprint $table) {
            $table->foreignId('continent_id')->nullable()->constrained('continents');
        });

        // Resolve continent codes already in the table
        $continentMap = DB::table('continents')->pluck('id', 'code')->all();

        foreach ($continentMap as $code => $id) {
            DB::table('regions')
                ->where('continent', $code)
                ->update(['continent_id' => $id]);
        }

        // Now make it non-nullable and drop the old string column
        Schema::table('regions', function (Blueprint $table) {
            $table->foreignId('continent_id')->nullable(false)->change();
            $table->dropColumn('continent');
        });
    }

    public function down(): void
    {
        Schema::table('regions', function (Blueprint $table) {
            $table->string('continent', 2);
        });

        $continentMap = DB::table('continents')->pluck('code', 'id')->all();

        foreach ($continentMap as $id => $code) {
            DB::table('regions')
                ->where('continent_id', $id)
                ->update(['continent' => $code]);
        }

        Schema::table('regions', function (Blueprint $table) {
            $table->dropConstrainedForeignId('continent_id');
        });
    }
};
