package tech.easyflow.skill.mapper;

import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * 标准 Skill 持久化收敛迁移的不可逆操作守卫测试。
 */
public class SkillStandardCleanupMigrationContractTest {

    /**
     * 数据完整性与私有包守卫必须先于任何旧表删除。
     *
     * @throws Exception 读取迁移文件失败时抛出
     */
    @Test
    public void guardsRunBeforeDestructiveCleanup() throws Exception {
        String sql = migrationSql();
        int firstDrop = sql.indexOf("DROP TABLE IF EXISTS `tb_skill_capability_binding`");

        assertTrue(firstDrop > 0);
        assertTrue(sql.indexOf("tmp_skill_standard_cleanup_guard") < firstDrop);
        assertTrue(sql.indexOf("resource.`tenant_id` <> skill.`tenant_id`") < firstDrop);
        assertTrue(sql.indexOf("WHERE `format` <> ''STANDARD''") < firstDrop);
    }

    /**
     * 迁移仅删除旧包表和派生字段，保留六张标准 Skill 表。
     *
     * @throws Exception 读取迁移文件失败时抛出
     */
    @Test
    public void keepsOnlyStandardPackagePersistence() throws Exception {
        String sql = migrationSql();

        for (String legacyTable : new String[]{
                "tb_skill_capability_binding",
                "tb_skill_reference",
                "tb_skill_script",
                "tb_skill_asset",
                "tb_skill_asset_content"
        }) {
            assertTrue(sql.contains("DROP TABLE IF EXISTS `" + legacyTable + "`"));
        }
        for (String standardTable : new String[]{
                "tb_skill_category",
                "tb_skill_resource",
                "tb_skill_content",
                "tb_skill_content_write_intent",
                "tb_skill_import_stage"
        }) {
            assertFalse(sql.contains("DROP TABLE IF EXISTS `" + standardTable + "`"));
        }
        assertTrue(sql.contains("'metadata_json', 'enabled', 'source_type', 'capability_hash'"));
        assertTrue(sql.contains("'kind', 'language', 'metadata_json', 'sort_no'"));
        assertTrue(sql.contains("ALTER TABLE `tb_skill_import_stage` DROP COLUMN `format`"));
    }

    private String migrationSql() throws Exception {
        Path root = Path.of("").toAbsolutePath();
        for (int level = 0; level < 5 && root != null; level++, root = root.getParent()) {
            Path migration = root.resolve("easyflow-starter/easyflow-starter-all/src/main/resources/"
                    + "db/migration/mysql/V55__mysql_skill_standard_package_cleanup.sql");
            if (Files.isRegularFile(migration)) {
                return Files.readString(migration, StandardCharsets.UTF_8);
            }
        }
        throw new IllegalStateException("未找到 V55 Skill 标准化迁移脚本");
    }
}
