<?php

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

/**
 * item_fields 테이블에 field_key 및 잠금 컬럼 추가
 *
 * 변경 내용:
 * 1. field_key: 필드 고유 식별자 ({ID}_{key} 형식, unique)
 * 2. is_locked: 엔티티 자체 잠금 여부
 * 3. locked_by: 잠금 설정자 ID
 * 4. locked_at: 잠금 설정 일시
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('item_fields', function (Blueprint $table) {
            $table->string('field_key', 100)->nullable()->after('field_name')->comment('필드 고유 키 ({ID}_{key} 형식)');
            $table->boolean('is_locked')->default(false)->after('is_common')->comment('잠금 여부');
            $table->unsignedBigInteger('locked_by')->nullable()->after('is_locked')->comment('잠금 설정자 ID');
            $table->timestamp('locked_at')->nullable()->after('locked_by')->comment('잠금 설정 일시');

            // 인덱스
            $table->unique(['tenant_id', 'field_key'], 'uq_item_fields_tenant_field_key');
            $table->index('is_locked', 'idx_item_fields_is_locked');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('item_fields', function (Blueprint $table) {
            $table->dropUnique('uq_item_fields_tenant_field_key');
            $table->dropIndex('idx_item_fields_is_locked');
            $table->dropColumn(['field_key', 'is_locked', 'locked_by', 'locked_at']);
        });
    }
};
