package tech.easyflow.approval.service.impl;

import org.junit.Test;

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

import static org.junit.Assert.assertTrue;

/**
 * V37 审批多对象迁移契约测试。
 */
public class ApprovalMultiAssigneeMigrationContractTest {

    /**
     * 验证迁移先阻断在途审批，再创建关联表并完整回填配置和历史任务。
     *
     * @throws Exception 迁移文件不可读时抛出
     */
    @Test
    public void migrationShouldGuardAndBackfillBothAssigneeRelations() throws Exception {
        String sql = migrationSql();

        assertTrue(sql.contains("WHERE `status` IN ('PENDING', 'PROCESSING')"));
        assertTrue(sql.contains("WHERE `status` = 'PENDING'"));
        assertTrue(sql.contains("SIGNAL SQLSTATE '45000'"));
        assertTrue(sql.indexOf("CALL `sp_guard_approval_multi_assignee`()")
                < sql.indexOf("CREATE TABLE IF NOT EXISTS `tb_approval_flow_step_assignee`"));
        assertTrue(sql.contains("CREATE TABLE IF NOT EXISTS `tb_approval_task_assignee`"));
        assertTrue(sql.contains("UNIQUE KEY `uk_approval_step_assignee`"));
        assertTrue(sql.contains("UNIQUE KEY `uk_approval_task_assignee`"));
        assertTrue(sql.contains("FROM `tb_approval_flow_step` step"));
        assertTrue(sql.contains("FROM `tb_approval_task` task"));
        assertTrue(sql.contains("approval multi-assignee backfill verification failed"));
    }

    /**
     * 读取工作区中的 V37 MySQL 迁移。
     *
     * @return 迁移 SQL
     * @throws Exception 迁移文件不存在或不可读时抛出
     */
    private String migrationSql() throws Exception {
        Path root = Path.of(System.getProperty("maven.multiModuleProjectDirectory",
                Path.of(System.getProperty("user.dir")).toAbsolutePath().toString()));
        while (root != null) {
            Path migration = root.resolve("easyflow-starter/easyflow-starter-all/src/main/resources/"
                    + "db/migration/mysql/V37__mysql_approval_multi_assignee.sql");
            if (Files.isRegularFile(migration)) {
                return Files.readString(migration, StandardCharsets.UTF_8);
            }
            root = root.getParent();
        }
        throw new IllegalStateException("找不到 V37 审批多对象迁移");
    }
}
