<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 템플릿별 외부 키 매핑 정의
        Schema::create('document_template_links', function (Blueprint $table) {
            $table->id();
            $table->foreignId('template_id')->constrained('document_templates')->cascadeOnDelete();
            $table->string('link_key', 50)->comment('UI 식별 키 (items, process, lot)');
            $table->string('label', 50)->comment('표시명 (연결 품목, 연결 공정)');
            $table->string('link_type', 20)->default('single')->comment('single|multiple');
            $table->string('search_api', 255)->comment('검색 API (/api/admin/items/search)');
            $table->json('search_params')->nullable()->comment('API 추가 파라미터');
            $table->json('display_fields')->nullable()->comment('표시 필드 (title, subtitle)');
            $table->boolean('is_required')->default(false);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['template_id', 'sort_order'], 'idx_tpl_link_sort');
        });

        // 템플릿 레벨 연결 값 (기존 linked_item_ids/linked_process_id 대체)
        Schema::create('document_template_link_values', function (Blueprint $table) {
            $table->id();
            $table->foreignId('template_id')->constrained('document_templates')->cascadeOnDelete();
            $table->foreignId('link_id')->constrained('document_template_links')->cascadeOnDelete();
            $table->unsignedBigInteger('linkable_id')->comment('연결 대상 PK');
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamp('created_at')->nullable();

            $table->index(['link_id', 'linkable_id'], 'idx_link_value');
        });

        // 문서 레벨 연결 (기존 linkable_type/linkable_id 대체)
        Schema::create('document_links', function (Blueprint $table) {
            $table->id();
            $table->foreignId('document_id')->constrained('documents')->cascadeOnDelete();
            $table->unsignedBigInteger('link_id')->comment('FK: document_template_links');
            $table->unsignedBigInteger('linkable_id');
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamp('created_at')->nullable();

            $table->index(['document_id', 'link_id'], 'idx_doc_link');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('document_links');
        Schema::dropIfExists('document_template_link_values');
        Schema::dropIfExists('document_template_links');
    }
};
