<?php

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

/**
 * The Bin Card — immutable, append-only ledger of every stock change.
 *
 * Writes flow exclusively through StockMovementService. There are no
 * `updated_at` or `deleted_at` columns on purpose — rows are never modified.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('stock_movements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('branch_id')->constrained('warehouses')->cascadeOnUpdate()->cascadeOnDelete();
            $table->unsignedBigInteger('product_id'); // FK added in Phase 2 with products. Mirrors branch_stock(branch_id, product_id).
            $table->foreignId('movement_type_id')->constrained('movement_types')->cascadeOnUpdate()->restrictOnDelete();

            // Polymorphic reference to the parent record (invoice, GRN, return, damage, etc.)
            $table->string('reference_type', 100)->nullable();
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->string('reference_number', 50)->nullable(); // legacy compat: surfaces in Bin Card UI

            $table->decimal('quantity_before', 12, 4);
            $table->decimal('quantity_change', 12, 4);
            $table->decimal('quantity_after', 12, 4);
            $table->decimal('unit_cost', 12, 2)->nullable();
            $table->text('note')->nullable();

            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['branch_id', 'product_id', 'created_at']);
            $table->index(['reference_type', 'reference_id']);
            $table->index('movement_type_id');
        });
    }

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