<?php

/**
 * 文件功能：将猜成语数据结构升级为猜谜活动通用结构
 *
 * 为题库增加题型字段，为回合增加 quiz_type 与复合索引，
 * 兼容既有“猜成语”数据并为脑筋急转弯题型预留能力。
 */

use App\Models\Riddle;
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
{
    /**
     * 方法功能：执行表结构升级并补齐历史数据默认值。
     */
    public function up(): void
    {
        Schema::table('idioms', function (Blueprint $table): void {
            if (! Schema::hasColumn('idioms', 'type')) {
                $table->string('type', 30)->default(Riddle::TYPE_IDIOM)->after('id')->comment('题型：idiom/brain_teaser');
            }
        });

        // 历史成语题默认归类到 idiom，保证旧数据无需人工修复。
        DB::table('idioms')
            ->whereNull('type')
            ->orWhere('type', '')
            ->update(['type' => Riddle::TYPE_IDIOM]);

        Schema::table('idiom_game_rounds', function (Blueprint $table): void {
            if (! Schema::hasColumn('idiom_game_rounds', 'quiz_type')) {
                $table->string('quiz_type', 30)->default(Riddle::TYPE_IDIOM)->after('idiom_id')->comment('回合题型：idiom/brain_teaser');
            }
        });

        // 历史回合默认按成语题处理，确保旧记录仍可正常展示与过期结算。
        DB::table('idiom_game_rounds')
            ->whereNull('quiz_type')
            ->orWhere('quiz_type', '')
            ->update(['quiz_type' => Riddle::TYPE_IDIOM]);

        Schema::table('idioms', function (Blueprint $table): void {
            $table->index(['type', 'is_active'], 'idioms_type_is_active_index');
        });

        Schema::table('idiom_game_rounds', function (Blueprint $table): void {
            $table->index(['room_id', 'quiz_type', 'status'], 'idiom_rounds_room_type_status_index');
            $table->index(['room_id', 'quiz_type', 'id'], 'idiom_rounds_room_type_id_index');
        });
    }

    /**
     * 方法功能：回滚猜谜活动通用结构升级。
     */
    public function down(): void
    {
        Schema::table('idiom_game_rounds', function (Blueprint $table): void {
            $table->dropIndex('idiom_rounds_room_type_status_index');
            $table->dropIndex('idiom_rounds_room_type_id_index');
            $table->dropColumn('quiz_type');
        });

        Schema::table('idioms', function (Blueprint $table): void {
            $table->dropIndex('idioms_type_is_active_index');
            $table->dropColumn('type');
        });
    }
};
