<?php

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

/**
 * 검사양식/작업일지 설정을 ProcessStep → Process 레벨로 이동
 * - processes: document_template_id, needs_work_log, work_log_template_id 추가
 * - process_steps: document_template_id 제거
 */
return new class extends Migration
{
    public function up(): void
    {
        // 1. Process에 검사양식/작업일지 필드 추가
        Schema::table('processes', function (Blueprint $table) {
            $table->foreignId('document_template_id')->nullable()->after('work_log_template')
                ->constrained('document_templates')->nullOnDelete()->comment('중간검사 양식 ID');
            $table->boolean('needs_work_log')->default(false)->after('document_template_id')->comment('작업일지 여부');
            $table->foreignId('work_log_template_id')->nullable()->after('needs_work_log')
                ->constrained('document_templates')->nullOnDelete()->comment('작업일지 양식 ID');
        });

        // 2. ProcessStep에서 document_template_id 제거
        Schema::table('process_steps', function (Blueprint $table) {
            $table->dropForeign(['document_template_id']);
            $table->dropColumn('document_template_id');
        });
    }

    public function down(): void
    {
        // ProcessStep에 document_template_id 복원
        Schema::table('process_steps', function (Blueprint $table) {
            $table->foreignId('document_template_id')->nullable()->after('needs_inspection')
                ->constrained('document_templates')->nullOnDelete();
        });

        // Process에서 필드 제거
        Schema::table('processes', function (Blueprint $table) {
            $table->dropForeign(['work_log_template_id']);
            $table->dropForeign(['document_template_id']);
            $table->dropColumn(['work_log_template_id', 'needs_work_log', 'document_template_id']);
        });
    }
};
