<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('inventory_movements', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('product_id')->constrained('products');
            $table->foreignId('warehouse_id')->constrained('warehouses');
            $table->string('movement_type', 30);
            $table->string('direction', 5);
            $table->integer('quantity');
            $table->integer('quantity_before');
            $table->integer('quantity_after');
            $table->bigInteger('unit_cost')->nullable();
            $table->bigInteger('total_cost')->nullable();
            $table->string('reference_type')->nullable();
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->string('batch_number')->nullable();
            $table->date('expiry_date')->nullable();
            $table->text('reason')->nullable();
            $table->foreignId('created_by')->constrained('users');
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            // Composite indexes
            $table->index(['academy_id', 'product_id', 'warehouse_id'], 'inv_mov_academy_product_warehouse_idx');
            $table->index(['movement_type', 'direction'], 'inv_mov_type_direction_idx');
            $table->index(['product_id', 'created_at'], 'inv_mov_product_created_idx');
            $table->index(['reference_type', 'reference_id'], 'inv_mov_reference_idx');
            $table->index('created_at');
        });

        DB::statement("ALTER TABLE inventory_movements ADD CONSTRAINT inventory_movements_movement_type_check CHECK (movement_type IN ('purchase_received', 'sale', 'transfer_out', 'transfer_in', 'return_to_stock', 'return_to_supplier', 'adjustment_up', 'adjustment_down', 'damage', 'loss', 'consumption', 'kit_assembly', 'kit_disassembly', 'initial_stock', 'count_adjustment_up', 'count_adjustment_down'))");

        DB::statement("ALTER TABLE inventory_movements ADD CONSTRAINT inventory_movements_direction_check CHECK (direction IN ('in', 'out'))");
    }

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