<?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
    {
        Schema::create('bag_exchanges', function (Blueprint $table) {
            // Consistent engine/collation
            $table->engine    = 'InnoDB';
            $table->charset   = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';

            $table->id(); // BIGINT UNSIGNED

            // FK columns (constraints added in next migration)
            $table->unsignedBigInteger('company_id')->nullable(); // Index in dump
            $table->string('invoice_no', 191)->nullable();

            $table->unsignedBigInteger('warehouse_id')->nullable();
            $table->unsignedBigInteger('product_id')->nullable();
            $table->decimal('quantity', 8, 2)->nullable();

            $table->unsignedBigInteger('exchange_product_id')->nullable();
            $table->decimal('exchange_quantity', 8, 2)->nullable();

            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();

            $table->timestamps();

            $table->unsignedBigInteger('exchange_warehouse_id')->nullable();
            $table->date('date')->nullable();

            // Bag-related fields
            $table->unsignedBigInteger('bag_id')->nullable();
            $table->unsignedBigInteger('exchange_bag_id')->nullable();
            $table->unsignedBigInteger('bag_warehouse_id')->nullable();
            $table->unsignedBigInteger('bag_exchange_warehouse_id')->nullable();

            // Indexes (short names to avoid 64-char limit)
            $table->index('company_id',                 'be_company_idx');
            $table->index('invoice_no',                 'be_invoice_idx');
            $table->index('warehouse_id',               'be_wh_idx');
            $table->index('product_id',                 'be_product_idx');
            $table->index('exchange_product_id',        'be_ex_product_idx');
            $table->index('exchange_warehouse_id',      'be_ex_wh_idx');
            $table->index('created_by',                 'be_created_by_idx');
            $table->index('updated_by',                 'be_updated_by_idx');
            $table->index('date',                       'be_date_idx');

            $table->index('bag_id',                     'be_bag_idx');
            $table->index('exchange_bag_id',            'be_ex_bag_idx');
            $table->index('bag_warehouse_id',           'be_bag_wh_idx');
            $table->index('bag_exchange_warehouse_id',  'be_ex_bag_wh_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('bag_exchanges');
    }
};

