<?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.
     * sales_scenario_checklists 테이블에 필요한 컬럼 추가
     */
    public function up(): void
    {
        Schema::table('sales_scenario_checklists', function (Blueprint $table) {
            // scenario_type 컬럼 추가 (sales/manager 구분)
            if (!Schema::hasColumn('sales_scenario_checklists', 'scenario_type')) {
                $table->enum('scenario_type', ['sales', 'manager'])->default('sales')->after('tenant_id')->comment('시나리오 유형');
            }

            // checkpoint_id 컬럼 추가 (문자열 ID)
            if (!Schema::hasColumn('sales_scenario_checklists', 'checkpoint_id')) {
                $table->string('checkpoint_id', 50)->nullable()->after('step_id')->comment('체크포인트 ID');
            }

            // checked_at 컬럼 추가
            if (!Schema::hasColumn('sales_scenario_checklists', 'checked_at')) {
                $table->timestamp('checked_at')->nullable()->after('is_checked')->comment('체크 일시');
            }

            // checked_by 컬럼 추가 (user_id를 대체)
            if (!Schema::hasColumn('sales_scenario_checklists', 'checked_by')) {
                $table->unsignedBigInteger('checked_by')->nullable()->after('checked_at')->comment('체크한 사용자 ID');
            }

            // memo 컬럼 추가
            if (!Schema::hasColumn('sales_scenario_checklists', 'memo')) {
                $table->text('memo')->nullable()->after('checked_by')->comment('메모');
            }
        });

        // 인덱스 추가 (존재 여부 확인)
        $indexExists = DB::select("SHOW INDEX FROM sales_scenario_checklists WHERE Key_name = 'sales_scenario_checklists_tenant_id_scenario_type_index'");
        if (empty($indexExists)) {
            Schema::table('sales_scenario_checklists', function (Blueprint $table) {
                $table->index(['tenant_id', 'scenario_type']);
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('sales_scenario_checklists', function (Blueprint $table) {
            $columns = ['scenario_type', 'checkpoint_id', 'checked_at', 'checked_by', 'memo'];
            foreach ($columns as $column) {
                if (Schema::hasColumn('sales_scenario_checklists', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
