<?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
    {
        if (!Schema::hasTable('rm_order_delivery_details')) return;

        Schema::table('rm_order_delivery_details', function (Blueprint $table) {
            // Exactly as in your dump:
            //   rm_order_delivery_details_product_id_foreign
            //   rm_order_delivery_details_delivery_id_foreign
            if (!Schema::hasColumn('rm_order_delivery_details', 'product_id')) return;
            if (!Schema::hasColumn('rm_order_delivery_details', 'delivery_id')) return;

            $table->foreign('product_id', 'rm_order_delivery_details_product_id_foreign')
                  ->references('id')->on('products')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();

            $table->foreign('delivery_id', 'rm_order_delivery_details_delivery_id_foreign')
                  ->references('id')->on('rm_order_deliveries')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();
        });
    }

    public function down(): void
    {
        if (!Schema::hasTable('rm_order_delivery_details')) return;

        Schema::table('rm_order_delivery_details', function (Blueprint $table) {
            try { $table->dropForeign('rm_order_delivery_details_product_id_foreign'); } catch (\Throwable $e) {}
            try { $table->dropForeign('rm_order_delivery_details_delivery_id_foreign'); } catch (\Throwable $e) {}
        });
    }
};

