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;

import java.util.List;
import java.util.Map;

/**
 * Flyway 迁移历史查看和清理工具
 */
@SpringBootTest
@ActiveProfiles("dev")
public class FlywayHistoryTool {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查看迁移历史
     */
    @Test
    public void showHistory() {
        System.out.println("=== Flyway 迁移历史 ===");
        List<Map<String, Object>> history = jdbcTemplate.queryForList(
            "SELECT version, description, type, script, checksum, installed_by, installed_on, execution_time, success " +
            "FROM flyway_schema_history " +
            "ORDER BY installed_rank DESC"
        );

        for (Map<String, Object> row : history) {
            System.out.printf("Version: %-10s | Type: %-15s | Script: %-50s | Success: %s | Installed: %s%n",
                row.get("version"),
                row.get("type"),
                row.get("script"),
                row.get("success"),
                row.get("installed_on")
            );
        }
    }

    /**
     * 清理版本 20 的迁移记录
     */
    @Test
    public void cleanV20() {
        System.out.println("=== 清理版本 20 的迁移记录 ===");

        // 查看版本 20 的记录
        List<Map<String, Object>> v20Records = jdbcTemplate.queryForList(
            "SELECT * FROM flyway_schema_history WHERE version = '20'"
        );

        if (v20Records.isEmpty()) {
            System.out.println("没有找到版本 20 的记录");
            return;
        }

        System.out.println("找到 " + v20Records.size() + " 条版本 20 的记录:");
        for (Map<String, Object> row : v20Records) {
            System.out.printf("  - ID: %s, Script: %s, Success: %s%n",
                row.get("installed_rank"), row.get("script"), row.get("success"));
        }

        // 删除版本 20 的所有记录
        int deleted = jdbcTemplate.update("DELETE FROM flyway_schema_history WHERE version = '20'");
        System.out.println("已删除 " + deleted + " 条记录");
        System.out.println("请重启应用，Flyway 会重新执行 V20 迁移");
    }
}
