<?php

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

return new class extends Migration
{
    public function up(): void
{
    Schema::table('shipping_rates', function (Blueprint $table) {
        // 1. Cek: Kalau kolom LAMA masih ada, baru dihapus
        if (Schema::hasColumn('shipping_rates', 'destination_district_id')) {
            // Hapus foreign key dulu (bungkus try-catch biar gak error kalau key udah ilang)
            try {
                $table->dropForeign(['destination_district_id']);
            } catch (\Exception $e) {}
            
            $table->dropColumn('destination_district_id');
        }

        // 2. Cek: Kalau kolom BARU belum ada, baru dibuat
        if (!Schema::hasColumn('shipping_rates', 'destination_village_id')) {
            $table->unsignedBigInteger('destination_village_id')->after('origin_city_id');
        }
    });

    // 3. Pasang Foreign Key (Di blok terpisah agar lebih aman)
    Schema::table('shipping_rates', function (Blueprint $table) {
        // Hapus foreign key baru jika sisa kegagalan sebelumnya (biar gak duplicate)
        try {
            $table->dropForeign(['destination_village_id']);
        } catch (\Exception $e) {}

        // Pasang ulang
        $table->foreign('destination_village_id')
              ->references('id')
              ->on('m_villages') // Pastikan nama tabel ini benar
              ->onUpdate('RESTRICT')
              ->onDelete('CASCADE');
    });
}

    public function down(): void
    {
        Schema::table('shipping_rates', function (Blueprint $table) {
            // Balikin lagi ke Kecamatan kalau di-rollback
            $table->dropForeign(['destination_village_id']);
            $table->dropColumn('destination_village_id');

            $table->unsignedBigInteger('destination_district_id')->after('origin_city_id');
            $table->foreign('destination_district_id')
                  ->references('id')
                  ->on('m_districts')
                  ->onUpdate('RESTRICT')
                  ->onDelete('CASCADE');
        });
    }
};