<?php

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

/**
 * processes 테이블에 options JSON 컬럼 추가
 * - needs_work_log 컬럼 → options.needs_work_log로 이동
 * - options.needs_inspection 신규 추가
 * - FK 컬럼(document_template_id, work_log_template_id)은 유지
 */
return new class extends Migration
{
    public function up(): void
    {
        // 1. options JSON 컬럼 추가
        Schema::table('processes', function (Blueprint $table) {
            $table->json('options')->nullable()->after('work_log_template_id')->comment('공정 설정 (needs_work_log, needs_inspection 등)');
        });

        // 2. 기존 needs_work_log 데이터를 options로 이동
        DB::table('processes')->orderBy('id')->each(function ($process) {
            DB::table('processes')->where('id', $process->id)->update([
                'options' => json_encode([
                    'needs_work_log' => (bool) $process->needs_work_log,
                    'needs_inspection' => false,
                ]),
            ]);
        });

        // 3. needs_work_log 컬럼 제거
        Schema::table('processes', function (Blueprint $table) {
            $table->dropColumn('needs_work_log');
        });
    }

    public function down(): void
    {
        // 1. needs_work_log 컬럼 복원
        Schema::table('processes', function (Blueprint $table) {
            $table->boolean('needs_work_log')->default(false)->after('document_template_id')->comment('작업일지 여부');
        });

        // 2. options에서 needs_work_log 데이터 복원
        DB::table('processes')->whereNotNull('options')->each(function ($process) {
            $options = json_decode($process->options, true);
            DB::table('processes')->where('id', $process->id)->update([
                'needs_work_log' => $options['needs_work_log'] ?? false,
            ]);
        });

        // 3. options 컬럼 제거
        Schema::table('processes', function (Blueprint $table) {
            $table->dropColumn('options');
        });
    }
};