<?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 which product master table exists
        $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_return_details', function (Blueprint $table) {
            // Parent sale return (nullable → cascade delete details with parent)
            if (Schema::hasTable('acc_sale_returns')) {
                $table->foreign('sale_return_id', 'asrd_parent_fk')
                      ->references('id')->on('acc_sale_returns')
                      ->onUpdate('cascade')
                      ->onDelete('cascade');
            }

            // Link to original sale line (nullable → set null)
            if (Schema::hasTable('acc_sale_details')) {
                $table->foreign('sale_detail_id', 'asrd_detail_fk')
                      ->references('id')->on('acc_sale_details')
                      ->onUpdate('cascade')
                      ->onDelete('set null');
            }
        });

        // Product FK (required)
        if ($productTable) {
            Schema::table('acc_sale_return_details', function (Blueprint $table) use ($productTable) {
                $table->foreign('product_id', 'asrd_product_fk')
                      ->references('id')->on($productTable)
                      ->onUpdate('cascade')
                      ->onDelete('restrict');
            });
        }
    }

    public function down(): void
    {
        Schema::table('acc_sale_return_details', function (Blueprint $table) {
            // Drop by names; guard if some weren’t created
            try { $table->dropForeign('asrd_parent_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('asrd_detail_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('asrd_product_fk'); } catch (\Throwable $e) {}
        });
    }
};

