<?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
    {
        // Detect parent table (prefer returns; fallback to exchanges if that's what you have)
        $parentTable = null;
        if (Schema::hasTable('acc_sale_returns')) {
            $parentTable = 'acc_sale_returns';
        } elseif (Schema::hasTable('acc_sale_exchanges')) {
            $parentTable = 'acc_sale_exchanges';
        }

        // Detect product master table
        $productTable = null;
        if (Schema::hasTable('products')) {
            $productTable = 'products';
        } elseif (Schema::hasTable('finish_products')) {
            $productTable = 'finish_products';
        } elseif (Schema::hasTable('raw_materials')) {
            $productTable = 'raw_materials';
        }

        Schema::table('acc_sale_exchange_details', function (Blueprint $table) use ($parentTable, $productTable) {
            if ($parentTable) {
                $table->foreign('sale_return_id', 'ased_parent_fk')
                      ->references('id')->on($parentTable)
                      ->onUpdate('cascade')
                      ->onDelete('cascade'); // delete details with parent
            }

            if ($productTable) {
                $table->foreign('product_id', 'ased_product_fk')
                      ->references('id')->on($productTable)
                      ->onUpdate('cascade')
                      ->onDelete('restrict');
            }
        });
    }

    public function down(): void
    {
        Schema::table('acc_sale_exchange_details', function (Blueprint $table) {
            // Drop by names; guard in case they weren't created
            try { $table->dropForeign('ased_parent_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('ased_product_fk'); } catch (\Throwable $e) {}
        });
    }
};
