<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('item_fields', function (Blueprint $table) {
            $table->id()->comment('필드 ID');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');
            $table->unsignedBigInteger('section_id')->comment('섹션 ID');
            $table->string('field_name')->comment('필드명');
            $table->enum('field_type', ['textbox', 'number', 'dropdown', 'checkbox', 'date', 'textarea'])->comment('필드 타입');
            $table->integer('order_no')->default(0)->comment('정렬 순서');
            $table->boolean('is_required')->default(false)->comment('필수 여부');
            $table->text('default_value')->nullable()->comment('기본값');
            $table->string('placeholder')->nullable()->comment('플레이스홀더');
            $table->json('display_condition')->nullable()->comment('표시 조건 {"field_id": "1", "operator": "equals", "value": "true"}');
            $table->json('validation_rules')->nullable()->comment('검증 규칙 {"min": 0, "max": 100, "pattern": "regex"}');
            $table->json('options')->nullable()->comment('드롭다운 옵션 [{"label": "옵션1", "value": "val1"}]');
            $table->json('properties')->nullable()->comment('필드 속성 {"unit": "mm", "precision": 2, "format": "YYYY-MM-DD"}');
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자 ID');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');
            $table->timestamps();
            $table->softDeletes()->comment('소프트 삭제');

            // 인덱스
            $table->index(['tenant_id', 'section_id'], 'idx_item_fields_tenant_section');
            $table->index(['section_id', 'order_no'], 'idx_item_fields_order');

            // 외래키
            $table->foreign('tenant_id', 'fk_item_fields_tenant')
                ->references('id')->on('tenants')
                ->onDelete('cascade');
            $table->foreign('section_id', 'fk_item_fields_section')
                ->references('id')->on('item_sections')
                ->onDelete('cascade');
        });
    }

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