<?php
// database/migrations/xxxx_xx_xx_xxxxxx_create_inventory_movements_table.php

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

class CreateInventoryMovementsTable extends Migration
{
    public function up()
    {
        Schema::create('inventory_movements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained('product')->onDelete('restrict');
            
            // Tipo de movimiento: purchase, sale, adjustment, return_purchase, return_sale
            $table->enum('movement_type', [
                'purchase',      // Compra (entrada)
                'sale',          // Venta (salida)
                'adjustment',    // Ajuste manual
                'return_purchase', // Devolución a proveedor (salida)
                'return_sale'    // Devolución de cliente (entrada)
            ]);
            
            // Referencia al documento origen
            $table->string('reference_type'); // 'bill_detail' o 'sale_detail'
            $table->unsignedBigInteger('reference_id');
            
            $table->integer('quantity'); // Positivo = entrada, Negativo = salida
            $table->integer('stock_before')->nullable();
            $table->integer('stock_after')->nullable();
            
            // Costos para cálculos posteriores
            $table->decimal('unit_cost', 10, 2); // Costo unitario en el momento
            $table->decimal('total_cost', 10, 2); // quantity * unit_cost
            
            $table->text('notes')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users');
            
            $table->timestamps();
            
            // Índices para búsquedas rápidas
            $table->index(['reference_type', 'reference_id']);
            $table->index(['product_id', 'created_at']);
        });
    }

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