<?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('kardex', function (Blueprint $table) {
            $table->id();
            $table->foreignId('insumo_id')->constrained()->cascadeOnDelete();
            $table->foreignId('sucursal_id')->constrained('sucursales')->cascadeOnDelete();
            $table->enum('tipo', ['entrada', 'salida', 'ajuste']);
            $table->decimal('cantidad', 10, 3);
            $table->decimal('saldo_anterior', 10, 3);
            $table->decimal('saldo_posterior', 10, 3);
            $table->string('motivo', 200);
            $table->string('referencia_tipo', 50)->nullable(); // 'compra','picking','ajuste'
            $table->unsignedBigInteger('referencia_id')->nullable();
            $table->foreignId('user_id')->constrained()->restrictOnDelete();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['insumo_id', 'sucursal_id'], 'idx_kardex_insumo_suc');
            $table->index('created_at', 'idx_kardex_fecha');
            $table->index(['referencia_tipo', 'referencia_id'], 'idx_kardex_ref');
        });
    }

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