<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1. 기존 문자열 데이터를 JSON으로 변환
        DB::table('document_template_section_items')
            ->whereNotNull('tolerance')
            ->where('tolerance', '!=', '')
            ->orderBy('id')
            ->each(function ($row) {
                // 이미 JSON인 경우 스킵
                $decoded = json_decode($row->tolerance, true);
                if (is_array($decoded) && isset($decoded['type'])) {
                    return;
                }

                // 기존 문자열 → symmetric 타입으로 변환
                $value = trim($row->tolerance);
                $numericValue = preg_replace('/[^\d.]/', '', $value);

                $json = json_encode([
                    'type' => 'symmetric',
                    'value' => $numericValue !== '' ? (float) $numericValue : 0,
                ], JSON_UNESCAPED_UNICODE);

                DB::table('document_template_section_items')
                    ->where('id', $row->id)
                    ->update(['tolerance' => $json]);
            });

        // 2. 컬럼 타입 변경: VARCHAR → JSON
        Schema::table('document_template_section_items', function (Blueprint $table) {
            $table->json('tolerance')->nullable()->comment('공차/허용범위 (JSON)')->change();
        });
    }

    public function down(): void
    {
        Schema::table('document_template_section_items', function (Blueprint $table) {
            $table->string('tolerance', 100)->nullable()->comment('공차/허용범위')->change();
        });
    }
};
