package com.reading.platform;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.ActiveProfiles;

/**
 * Flyway 修复工具
 * 用于修复失败的数据库迁移
 *
 * 使用方法：
 * 1. 在 application-dev.yml 中添加：spring.flyway.enabled=false
 * 2. 运行此测试类：mvn test -Dtest=FlywayRepairTool#repairV20
 * 3. 恢复 Flyway 配置
 * 4. 重启应用
 */
@SpringBootTest
@ActiveProfiles("dev")
public class FlywayRepairTool {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 修复 V20 失败的迁移
     */
    @Test
    public void repairV20() {
        System.out.println("开始修复 Flyway V20 迁移...");

        // 删除 V20 的失败记录
        int rows = jdbcTemplate.update(
            "DELETE FROM flyway_schema_history WHERE version = '20'"
        );

        System.out.println("已删除 " + rows + " 条失败记录");
        System.out.println("修复完成！请重启应用。");
    }

    /**
     * 查看当前的迁移历史
     */
    @Test
    public void showMigrationHistory() {
        System.out.println("当前迁移历史：");
        jdbcTemplate.queryForList("SELECT * FROM flyway_schema_history ORDER BY installed_on DESC")
            .forEach(record -> {
                System.out.println("  Version: " + record.get("version") +
                                   ", Status: " + record.get("success") +
                                   ", Installed: " + record.get("installed_on"));
            });
    }
}
