<?php

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

return new class extends Migration
{
    /**
     * 기존 고정 필드 데이터를 동적 구조로 변환
     *
     * 1. 각 template에 대해 section_fields 레코드 생성
     * 2. linked_item_ids → template_links + link_values 변환
     * 3. linked_process_id → template_links + link_values 변환
     * 4. 각 section_item의 기존 컬럼값을 field_values JSON으로 변환
     */
    public function up(): void
    {
        // 기본 필드 정의 (기존 고정 컬럼 기반)
        $defaultFields = [
            ['field_key' => 'category', 'label' => '구분', 'field_type' => 'text', 'width' => '65px', 'is_required' => false, 'sort_order' => 0],
            ['field_key' => 'item', 'label' => '검사항목', 'field_type' => 'text', 'width' => '130px', 'is_required' => true, 'sort_order' => 1],
            ['field_key' => 'standard', 'label' => '검사기준', 'field_type' => 'text', 'width' => '180px', 'is_required' => false, 'sort_order' => 2],
            ['field_key' => 'standard_criteria', 'label' => '기준범위', 'field_type' => 'json_criteria', 'width' => '100px', 'is_required' => false, 'sort_order' => 3],
            ['field_key' => 'tolerance', 'label' => '공차/범위', 'field_type' => 'json_tolerance', 'width' => '120px', 'is_required' => false, 'sort_order' => 4],
            ['field_key' => 'method', 'label' => '검사방식', 'field_type' => 'select_api', 'width' => '110px', 'is_required' => false, 'sort_order' => 5, 'options' => json_encode([
                'api_endpoint' => '/api/admin/common-codes/inspection_method',
                'auto_map' => [
                    'target_field' => 'measurement_type',
                    'mapping' => [
                        'visual' => 'checkbox',
                        'check' => 'numeric',
                        'mill_sheet' => 'single_value',
                        'certified_agency' => 'single_value',
                        'substitute_cert' => 'substitute',
                        'other' => 'text',
                    ],
                ],
            ])],
            ['field_key' => 'measurement_type', 'label' => '측정유형', 'field_type' => 'select', 'width' => '100px', 'is_required' => false, 'sort_order' => 6, 'options' => json_encode([
                'choices' => [
                    ['code' => 'checkbox', 'name' => 'OK/NG 체크'],
                    ['code' => 'numeric', 'name' => '수치입력(3)'],
                    ['code' => 'single_value', 'name' => '단일값'],
                    ['code' => 'substitute', 'name' => '성적서 대체'],
                    ['code' => 'text', 'name' => '자유입력'],
                ],
            ])],
            ['field_key' => 'frequency', 'label' => '검사주기', 'field_type' => 'composite_frequency', 'width' => '120px', 'is_required' => false, 'sort_order' => 7],
            ['field_key' => 'regulation', 'label' => '관련규정', 'field_type' => 'text', 'width' => '80px', 'is_required' => false, 'sort_order' => 8],
        ];

        $now = now();

        // 1. 각 template에 section_fields 생성
        $templates = DB::table('document_templates')->get();

        foreach ($templates as $template) {
            // section_fields 생성
            foreach ($defaultFields as $field) {
                DB::table('document_template_section_fields')->insert([
                    'template_id' => $template->id,
                    'field_key' => $field['field_key'],
                    'label' => $field['label'],
                    'field_type' => $field['field_type'],
                    'options' => $field['options'] ?? null,
                    'width' => $field['width'],
                    'is_required' => $field['is_required'],
                    'sort_order' => $field['sort_order'],
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }

            // linked_item_ids → template_links + link_values
            $linkedItemIds = json_decode($template->linked_item_ids ?? '[]', true);
            if (! empty($linkedItemIds)) {
                $linkId = DB::table('document_template_links')->insertGetId([
                    'template_id' => $template->id,
                    'link_key' => 'items',
                    'label' => '연결 품목 (RM, SM)',
                    'link_type' => 'multiple',
                    'search_api' => '/api/admin/items/search',
                    'search_params' => json_encode(['item_type' => 'RM,SM']),
                    'display_fields' => json_encode(['title' => 'name', 'subtitle' => 'code']),
                    'is_required' => false,
                    'sort_order' => 0,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);

                foreach ($linkedItemIds as $idx => $itemId) {
                    DB::table('document_template_link_values')->insert([
                        'template_id' => $template->id,
                        'link_id' => $linkId,
                        'linkable_id' => $itemId,
                        'sort_order' => $idx,
                        'created_at' => $now,
                    ]);
                }
            }

            // linked_process_id → template_links + link_values
            if (! empty($template->linked_process_id)) {
                $linkId = DB::table('document_template_links')->insertGetId([
                    'template_id' => $template->id,
                    'link_key' => 'process',
                    'label' => '연결 공정',
                    'link_type' => 'single',
                    'search_api' => '/api/admin/processes/search',
                    'search_params' => null,
                    'display_fields' => json_encode(['title' => 'process_name', 'subtitle' => 'process_code']),
                    'is_required' => false,
                    'sort_order' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);

                DB::table('document_template_link_values')->insert([
                    'template_id' => $template->id,
                    'link_id' => $linkId,
                    'linkable_id' => $template->linked_process_id,
                    'sort_order' => 0,
                    'created_at' => $now,
                ]);
            }
        }

        // 2. 각 section_item의 기존 컬럼값을 field_values JSON으로 변환
        $items = DB::table('document_template_section_items')->get();

        foreach ($items as $item) {
            $fieldValues = [];

            if (! empty($item->category)) {
                $fieldValues['category'] = $item->category;
            }
            if (! empty($item->item)) {
                $fieldValues['item'] = $item->item;
            }
            if (! empty($item->standard)) {
                $fieldValues['standard'] = $item->standard;
            }
            if (! empty($item->standard_criteria)) {
                $decoded = json_decode($item->standard_criteria, true);
                $fieldValues['standard_criteria'] = $decoded ?? $item->standard_criteria;
            }
            if (! empty($item->tolerance)) {
                $decoded = json_decode($item->tolerance, true);
                $fieldValues['tolerance'] = $decoded ?? $item->tolerance;
            }
            if (! empty($item->method)) {
                $fieldValues['method'] = $item->method;
            }
            if (! empty($item->measurement_type)) {
                $fieldValues['measurement_type'] = $item->measurement_type;
            }
            if (! empty($item->frequency)) {
                $fieldValues['frequency'] = $item->frequency;
            }
            if (! empty($item->frequency_n)) {
                $fieldValues['frequency_n'] = $item->frequency_n;
            }
            if (! empty($item->frequency_c)) {
                $fieldValues['frequency_c'] = $item->frequency_c;
            }
            if (! empty($item->regulation)) {
                $fieldValues['regulation'] = $item->regulation;
            }

            if (! empty($fieldValues)) {
                DB::table('document_template_section_items')
                    ->where('id', $item->id)
                    ->update(['field_values' => json_encode($fieldValues, JSON_UNESCAPED_UNICODE)]);
            }
        }
    }

    public function down(): void
    {
        // section_fields 삭제
        DB::table('document_template_section_fields')->truncate();

        // link_values, links, document_links 삭제
        DB::table('document_template_link_values')->truncate();
        DB::table('document_template_links')->truncate();
        DB::table('document_links')->truncate();

        // field_values NULL로 초기화
        DB::table('document_template_section_items')->update(['field_values' => null]);
    }
};
