<?php

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

/**
 * files 테이블 수정
 *
 * 1. file_type: ENUM → VARCHAR(50) 변경 (확장성)
 * 2. field_key: VARCHAR(100) 추가 (비즈니스 용도 구분)
 */
return new class extends Migration
{
    public function up(): void
    {
        // 1. file_type ENUM → VARCHAR(50) 변경
        DB::statement("ALTER TABLE `files` MODIFY `file_type` VARCHAR(50) NULL DEFAULT NULL COMMENT '파일 형식 (image, document, excel, archive 등)'");

        // 2. field_key 컬럼 추가
        if (! Schema::hasColumn('files', 'field_key')) {
            Schema::table('files', function (Blueprint $table) {
                $table->string('field_key', 100)
                    ->nullable()
                    ->after('file_type')
                    ->comment('비즈니스 용도 구분 (drawing, certificate, specification 등)');

                // 인덱스 추가 (document_type + document_id + field_key 조합 조회용)
                $table->index(['document_type', 'document_id', 'field_key'], 'idx_files_document_field_key');
            });
        }
    }

    public function down(): void
    {
        // 1. field_key 컬럼 삭제
        if (Schema::hasColumn('files', 'field_key')) {
            Schema::table('files', function (Blueprint $table) {
                $table->dropIndex('idx_files_document_field_key');
                $table->dropColumn('field_key');
            });
        }

        // 2. file_type VARCHAR → ENUM 복원
        DB::statement("ALTER TABLE `files` MODIFY `file_type` ENUM('document','image','excel','archive') NOT NULL");
    }
};
