<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\Core\Enums\StatusEnum;
use Modules\Inventory\Enums\StockBatchStatusEnum;

return new class extends Migration
{
    /**
     * Run the migrations.HasInventoryDepartment
     */
    public function up(): void
    {
        Schema::create('stock_batches', function (Blueprint $table) {
            $table->id();
            $table->foreignId('stock_id')->constrained()->cascadeOnDelete();
            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
            $table->foreignId('inventory_department_id')->constrained()->cascadeOnDelete();
            $table->foreignId('purchase_invoice_item_id')->nullable()->constrained()->nullOnDelete();
            $table->string('batch_no')->nullable()->index();
            $table->date('manufacture_date')->nullable()->index();
            $table->date('expiry_date')->nullable();
            $table->decimal('qty', 20, 6)->comment('Total received quantity in base unit');
            $table->decimal('remaining_qty', 20, 6)->comment('Available quantity in base unit (after deducting reserved and damaged qty)');
            $table->decimal('reserved_qty', 20, 6)->default(0);
            $table->decimal('damaged_qty', 20, 6)->default(0);
            $table->decimal('consumed_qty', 20, 6)->default(0);
            $table->decimal('cost_price', 20, 6)->comment('Per base unit cost price');
            $table->decimal('total_cost', 20, 2)->comment('qty × cost_price');
            $table->enum('batch_status', StockBatchStatusEnum::casesAsArray())->index()->default(StockBatchStatusEnum::AVAILABLE->value);
            $table->enum('status', StatusEnum::casesAsArray())->index()->default(StatusEnum::ACTIVE);

            $table->timestamps();
            $table->softDeletes();
            $table->index(['expiry_date', 'remaining_qty']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('stock_batches');
    }
};
