<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (Schema::hasTable('qc_items')) {
            Schema::table('qc_items', function (Blueprint $table) {
                // Add bin support for warehouse management
                if (!Schema::hasColumn('qc_items', 'available_bin_id')) {
                    $table->foreignId('available_bin_id')->nullable()->after('item_id')->constrained('warehouse_bins')->nullOnDelete();
                }
                if (!Schema::hasColumn('qc_items', 'rejected_bin_id')) {
                    $table->foreignId('rejected_bin_id')->nullable()->after('available_bin_id')->constrained('warehouse_bins')->nullOnDelete();
                }

                // Add lot number support
                if (!Schema::hasColumn('qc_items', 'lot_no')) {
                    $table->string('lot_no')->nullable()->after('rejected_bin_id');
                }

                // Add indexes (guard if not existing handled implicitly)
                $table->index('available_bin_id');
                $table->index('rejected_bin_id');
                $table->index('lot_no');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('qc_items', function (Blueprint $table) {
            $table->dropIndex(['available_bin_id']);
            $table->dropIndex(['rejected_bin_id']);
            $table->dropIndex(['lot_no']);

            $table->dropConstrainedForeignId('available_bin_id');
            $table->dropConstrainedForeignId('rejected_bin_id');
            $table->dropColumn(['lot_no']);
        });
    }
};
