<?php

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

/**
 * 재고 LOT 테이블
 *
 * 재고의 LOT별 상세 정보를 관리합니다.
 * FIFO 기반 출고 관리에 사용됩니다.
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('stock_lots', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');
            $table->unsignedBigInteger('stock_id')->comment('재고 ID');

            // LOT 정보
            $table->string('lot_no', 50)->comment('LOT번호');
            $table->unsignedInteger('fifo_order')->default(1)->comment('FIFO 순서');
            $table->date('receipt_date')->comment('입고일');

            // 수량 정보
            $table->decimal('qty', 15, 3)->default(0)->comment('수량');
            $table->decimal('reserved_qty', 15, 3)->default(0)->comment('예약 수량');
            $table->decimal('available_qty', 15, 3)->default(0)->comment('가용 수량');
            $table->string('unit', 20)->default('EA')->comment('단위');

            // 공급업체 정보
            $table->string('supplier', 100)->nullable()->comment('공급업체');
            $table->string('supplier_lot', 50)->nullable()->comment('공급업체 LOT');
            $table->string('po_number', 50)->nullable()->comment('발주번호');

            // 위치 및 상태
            $table->string('location', 50)->nullable()->comment('위치');
            $table->string('status', 20)->default('available')
                ->comment('상태: available(사용가능), reserved(예약됨), used(사용완료)');

            // 연결 정보
            $table->unsignedBigInteger('receiving_id')->nullable()->comment('입고 ID');

            // 감사 정보
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자');
            $table->timestamps();
            $table->softDeletes();
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자');

            // 인덱스
            $table->index('tenant_id');
            $table->index('stock_id');
            $table->index('lot_no');
            $table->index('status');
            $table->index(['stock_id', 'fifo_order']);
            $table->unique(['tenant_id', 'stock_id', 'lot_no']);

            // 외래키
            $table->foreign('stock_id')->references('id')->on('stocks')->onDelete('cascade');
        });
    }

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