<?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('rm_bag_ledgers')) {
            Schema::create('rm_bag_ledgers', function (Blueprint $table) {
                $table->id(); // BIGINT UNSIGNED AI

                // Polymorphic source (no FK)
                $table->string('sourceable_type', 191);
                $table->unsignedBigInteger('sourceable_id');

                // FK columns (FKs will be added later)
                $table->unsignedBigInteger('bag_type_id')->nullable();
                $table->unsignedBigInteger('company_id')->nullable();
                $table->unsignedBigInteger('supplier_id')->nullable();
                $table->unsignedBigInteger('employee_id')->nullable();

                $table->date('date')->nullable();
                $table->decimal('quantity', 10, 2)->nullable();
                // reserved keywords are fine; Laravel will quote them
                $table->decimal('in',  10, 2)->nullable();
                $table->decimal('out', 10, 2)->nullable();
                $table->decimal('current_quantity', 10, 2)->nullable();
                $table->string('remarks', 191)->nullable();

                // created_by NOT NULL, updated_by NULL
                $table->unsignedBigInteger('created_by');
                $table->unsignedBigInteger('updated_by')->nullable();

                $table->timestamps();

                $table->unsignedBigInteger('warehouse_id')->nullable(); // no FK per dump

                // Helpful indexes (safe)
                $table->index('bag_type_id',  'rm_bag_ledgers_bag_type_id_index');
                $table->index('company_id',   'rm_bag_ledgers_company_id_index');
                $table->index('supplier_id',  'rm_bag_ledgers_supplier_id_index');
                $table->index('employee_id',  'rm_bag_ledgers_employee_id_index');
                $table->index('created_by',   'rm_bag_ledgers_created_by_index');
                $table->index('updated_by',   'rm_bag_ledgers_updated_by_index');
            });
        }
    }

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

