<?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('finish_bag_adjustment_details')) return;

        Schema::table('finish_bag_adjustment_details', function (Blueprint $table) {
            // Parent: finish_bag_adjustments.id
            if (Schema::hasTable('finish_bag_adjustments')) {
                $table->foreign('finish_bag_adjustment_id', 'fbad_parent_fk')
                      ->references('id')->on('finish_bag_adjustments')
                      ->onUpdate('cascade')
                      ->onDelete('cascade'); // delete details with parent
            }

            // Product reference (choose one target based on your schema)
            if (Schema::hasTable('finish_bags')) {
                $table->foreign('product_id', 'fbad_finish_bag_fk')
                      ->references('id')->on('finish_bags')
                      ->onUpdate('cascade')
                      ->onDelete('set null');
            }
            // If instead product_id → products.id, comment the above block and use this:
            // if (Schema::hasTable('products')) {
            //     $table->foreign('product_id', 'fbad_product_fk')
            //           ->references('id')->on('products')
            //           ->onUpdate('cascade')
            //           ->onDelete('set null');
            // }

            // Warehouse (nullable)
            if (Schema::hasTable('warehouses')) {
                $table->foreign('warehouse_id', 'fbad_warehouse_fk')
                      ->references('id')->on('warehouses')
                      ->onUpdate('cascade')
                      ->onDelete('set null');
            }
        });
    }

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

        Schema::table('finish_bag_adjustment_details', function (Blueprint $table) {
            foreach (['fbad_parent_fk','fbad_finish_bag_fk','fbad_product_fk','fbad_warehouse_fk'] as $fk) {
                try { $table->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};
