<?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('stock_movements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('inventory_item_id')->constrained()->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained(); // Who made the movement
            
            $table->enum('type', ['purchase', 'sale', 'adjustment', 'waste', 'transfer'])->default('adjustment');
            $table->enum('direction', ['in', 'out']); // Stock in or out
            
            $table->decimal('quantity', 10, 3);
            $table->decimal('unit_cost', 10, 2)->nullable();
            $table->decimal('total_cost', 10, 2)->nullable();
            
            $table->decimal('stock_before', 10, 3);
            $table->decimal('stock_after', 10, 3);
            
            $table->string('reference')->nullable(); // Order ID, Purchase Order, etc.
            $table->text('notes')->nullable();
            
            $table->timestamps();
            
            $table->index(['inventory_item_id', 'created_at']);
            $table->index(['branch_id', 'type', 'created_at']);
        });
    }

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