<?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
{
    /**
     * Align delivery_addresses with the customer city model: a nullable city_id
     * FK plus a legacy_city free-text fallback, replacing the required free-text
     * `city` column that caused NOT NULL violations on customer create.
     */
    public function up(): void
    {
        Schema::table('delivery_addresses', function (Blueprint $table) {
            $table->unsignedBigInteger('city_id')->nullable()->after('label');
            $table->string('legacy_city', 100)->nullable()->after('city_id');
        });

        // Preserve any existing free-text city values before dropping the column.
        DB::table('delivery_addresses')->update(['legacy_city' => DB::raw('city')]);

        Schema::table('delivery_addresses', function (Blueprint $table) {
            $table->dropColumn('city');
        });
    }

    public function down(): void
    {
        Schema::table('delivery_addresses', function (Blueprint $table) {
            $table->string('city', 100)->nullable()->after('label');
        });

        DB::table('delivery_addresses')->update(['city' => DB::raw('legacy_city')]);

        Schema::table('delivery_addresses', function (Blueprint $table) {
            $table->dropColumn(['city_id', 'legacy_city']);
        });
    }
};
