<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 테이블이 아직 없으면 스킵 (후속 마이그레이션에서 생성됨)
        if (! Schema::hasTable('sales_scenario_checklists')) {
            return;
        }

        // 기존 유니크 키가 존재하면 삭제
        $indexes = DB::select("SHOW INDEX FROM sales_scenario_checklists WHERE Key_name = 'sales_scenario_unique'");
        if (count($indexes) > 0) {
            Schema::table('sales_scenario_checklists', function (Blueprint $table) {
                $table->dropUnique('sales_scenario_unique');
            });
        }

        // checkpoint_index를 nullable로 변경
        Schema::table('sales_scenario_checklists', function (Blueprint $table) {
            $table->unsignedTinyInteger('checkpoint_index')->nullable()->change();
        });

        // 새 유니크 키가 존재하지 않으면 생성
        $newIndexes = DB::select("SHOW INDEX FROM sales_scenario_checklists WHERE Key_name = 'sales_scenario_checkpoint_unique'");
        if (count($newIndexes) === 0) {
            Schema::table('sales_scenario_checklists', function (Blueprint $table) {
                $table->unique(
                    ['tenant_id', 'scenario_type', 'step_id', 'checkpoint_id'],
                    'sales_scenario_checkpoint_unique'
                );
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 새 유니크 키가 존재하면 삭제
        $indexes = DB::select("SHOW INDEX FROM sales_scenario_checklists WHERE Key_name = 'sales_scenario_checkpoint_unique'");
        if (count($indexes) > 0) {
            Schema::table('sales_scenario_checklists', function (Blueprint $table) {
                $table->dropUnique('sales_scenario_checkpoint_unique');
            });
        }

        // checkpoint_index를 NOT NULL로 복원
        Schema::table('sales_scenario_checklists', function (Blueprint $table) {
            $table->unsignedTinyInteger('checkpoint_index')->nullable(false)->change();
        });

        // 기존 유니크 키가 존재하지 않으면 복원
        $oldIndexes = DB::select("SHOW INDEX FROM sales_scenario_checklists WHERE Key_name = 'sales_scenario_unique'");
        if (count($oldIndexes) === 0) {
            Schema::table('sales_scenario_checklists', function (Blueprint $table) {
                $table->unique(
                    ['tenant_id', 'user_id', 'step_id', 'checkpoint_index'],
                    'sales_scenario_unique'
                );
            });
        }
    }
};
