<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1) source_table 컬럼 추가
        Schema::table('document_template_links', function (Blueprint $table) {
            $table->string('source_table', 50)->nullable()->after('link_type')
                ->comment('소스 테이블 키 (system_field_definitions.source_table)');
        });

        // 2) 기존 search_api 데이터를 source_table로 변환
        $mapping = [
            '/api/admin/items/search' => 'items',
            '/api/admin/processes/search' => 'processes',
            '/api/admin/lots/search' => 'lots',
            '/api/admin/tenant-users/search' => 'users',
        ];

        foreach ($mapping as $api => $table) {
            DB::table('document_template_links')
                ->where('search_api', $api)
                ->update(['source_table' => $table]);
        }

        // 3) search_api 컬럼 삭제
        Schema::table('document_template_links', function (Blueprint $table) {
            $table->dropColumn('search_api');
        });
    }

    public function down(): void
    {
        Schema::table('document_template_links', function (Blueprint $table) {
            $table->string('search_api', 255)->after('link_type');
        });

        $mapping = [
            'items' => '/api/admin/items/search',
            'processes' => '/api/admin/processes/search',
            'lots' => '/api/admin/lots/search',
            'users' => '/api/admin/tenant-users/search',
        ];

        foreach ($mapping as $table => $api) {
            DB::table('document_template_links')
                ->where('source_table', $table)
                ->update(['search_api' => $api]);
        }

        Schema::table('document_template_links', function (Blueprint $table) {
            $table->dropColumn('source_table');
        });
    }
};
