<?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
{
    /**
     * 方法功能：删除 shop_items 中旧座驾记录并移除欢迎语字段。
     */
    public function up(): void
    {
        DB::table('shop_items')->where('slug', 'like', 'ride_%')->delete();

        if (DB::getDriverName() === 'mysql' && $this->shopItemTypeContainsRide()) {
            DB::statement("UPDATE `shop_items` SET `type` = 'one_time' WHERE `type` = 'ride'");
            DB::statement("ALTER TABLE `shop_items` MODIFY `type` ENUM('instant','duration','one_time','ring','auto_fishing','sign_repair','msg_bubble','msg_name_color','avatar_frame','msg_text_color') NOT NULL COMMENT '道具类型'");
        }

        if (Schema::hasColumn('shop_items', 'welcome_message')) {
            Schema::table('shop_items', function (Blueprint $table) {
                $table->dropColumn('welcome_message');
            });
        }
    }

    /**
     * 方法功能：清理迁移不恢复旧商店座驾结构。
     */
    public function down(): void
    {
        //
    }

    /**
     * 方法功能：判断当前 shop_items.type 枚举是否包含旧座驾类型。
     */
    private function shopItemTypeContainsRide(): bool
    {
        $column = DB::selectOne("SHOW COLUMNS FROM `shop_items` LIKE 'type'");

        return $column && str_contains((string) $column->Type, "'ride'");
    }
};
