<?php

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

/**
 * Phase 1.1: items 테이블 생성
 *
 * products + materials 통합 테이블
 * item_type: FG(완제품), PT(부품), SM(부자재), RM(원자재), CS(소모품)
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id()->comment('ID');
            $table->foreignId('tenant_id')->comment('테넌트 ID');

            // 기본 정보
            $table->string('item_type', 15)->comment('FG, PT, SM, RM, CS');
            $table->string('code', 100)->comment('품목코드');
            $table->string('name', 255)->comment('품목명');
            $table->string('unit', 20)->nullable()->comment('단위');
            $table->foreignId('category_id')->nullable()->comment('카테고리 ID');

            // BOM (JSON) - child_item_id, quantity
            $table->json('bom')->nullable()->comment('[{child_item_id, quantity}, ...]');

            // 동적 속성
            $table->json('attributes')->nullable()->comment('동적 필드 값');
            $table->json('attributes_archive')->nullable()->comment('속성 아카이브');
            $table->json('options')->nullable()->comment('추가 옵션');

            // 설명
            $table->text('description')->nullable()->comment('설명');

            // 상태
            $table->boolean('is_active')->default(true)->comment('활성 여부');

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

            // 인덱스
            $table->index(['tenant_id', 'item_type'], 'idx_items_tenant_type');
            $table->index(['tenant_id', 'code'], 'idx_items_tenant_code');
            $table->index(['tenant_id', 'category_id'], 'idx_items_tenant_category');
            $table->unique(['tenant_id', 'code', 'deleted_at'], 'uq_items_tenant_code');

            // 외래키
            $table->foreign('tenant_id')->references('id')->on('tenants');
            $table->foreign('category_id')->references('id')->on('categories')->nullOnDelete();
        });
    }

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