<?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_details', function (Blueprint $table) {
            // Parent sale (required) — delete details with sale
            if (Schema::hasTable('acc_sales')) {
                $table->foreign('sale_id', 'asd_sale_fk')
                      ->references('id')->on('acc_sales')
                      ->onUpdate('cascade')
                      ->onDelete('cascade');
            }
        });

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

    public function down(): void
    {
        Schema::table('acc_sale_details', function (Blueprint $table) {
            // Drop by names; guard in case some weren’t created
            try { $table->dropForeign('asd_sale_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('asd_product_fk'); } catch (\Throwable $e) {}
        });
    }
};

