<?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
{
    /**
     * Run the migrations.
     *
     * 1. item_sections에 is_template, description 컬럼 추가
     * 2. section_templates 데이터를 item_sections로 이관
     * 3. section_templates 테이블 제거
     */
    public function up(): void
    {
        // 1. item_sections에 is_template, description 컬럼 추가
        Schema::table('item_sections', function (Blueprint $table) {
            $table->boolean('is_template')->default(false)->after('order_no')->comment('템플릿 여부');
            $table->boolean('is_default')->default(false)->after('is_template')->comment('기본 템플릿 여부');
            $table->text('description')->nullable()->after('is_default')->comment('설명');
        });

        // 2. section_templates 데이터를 item_sections로 이관
        if (Schema::hasTable('section_templates')) {
            $templates = DB::table('section_templates')->whereNull('deleted_at')->get();

            foreach ($templates as $template) {
                DB::table('item_sections')->insert([
                    'tenant_id' => $template->tenant_id,
                    'group_id' => $template->group_id ?? 1,
                    'title' => $template->title,
                    'type' => $template->type,
                    'order_no' => 0,
                    'is_template' => true,
                    'is_default' => $template->is_default,
                    'description' => $template->description,
                    'created_by' => $template->created_by,
                    'updated_by' => $template->updated_by,
                    'created_at' => $template->created_at,
                    'updated_at' => $template->updated_at,
                ]);
            }

            // 3. section_templates 테이블 제거
            Schema::dropIfExists('section_templates');
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 1. section_templates 테이블 복원
        Schema::create('section_templates', function (Blueprint $table) {
            $table->id()->comment('섹션 템플릿 ID');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');
            $table->unsignedInteger('group_id')->default(1)->comment('그룹 ID');
            $table->string('title')->comment('템플릿명');
            $table->enum('type', ['fields', 'bom'])->default('fields')->comment('섹션 타입');
            $table->text('description')->nullable()->comment('설명');
            $table->boolean('is_default')->default(false)->comment('기본 템플릿 여부');
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자 ID');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');
            $table->timestamps();
            $table->softDeletes()->comment('소프트 삭제');

            $table->index('tenant_id', 'idx_section_templates_tenant_id');
            $table->foreign('tenant_id', 'fk_section_templates_tenant')
                ->references('id')->on('tenants')
                ->onDelete('cascade');
        });

        // 2. item_sections의 is_template=true 데이터를 section_templates로 이관
        $templates = DB::table('item_sections')
            ->where('is_template', true)
            ->whereNull('deleted_at')
            ->get();

        foreach ($templates as $template) {
            DB::table('section_templates')->insert([
                'tenant_id' => $template->tenant_id,
                'group_id' => $template->group_id,
                'title' => $template->title,
                'type' => $template->type,
                'description' => $template->description,
                'is_default' => $template->is_default,
                'created_by' => $template->created_by,
                'updated_by' => $template->updated_by,
                'created_at' => $template->created_at,
                'updated_at' => $template->updated_at,
            ]);
        }

        // 3. item_sections에서 is_template=true 데이터 삭제
        DB::table('item_sections')->where('is_template', true)->delete();

        // 4. item_sections에서 컬럼 제거
        Schema::table('item_sections', function (Blueprint $table) {
            $table->dropColumn(['is_template', 'is_default', 'description']);
        });
    }
};
