package tech.easyflow.ai.share;

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;

/**
 * V34 工作流分享与审批说明迁移契约测试。
 */
public class WorkflowShareMigrationContractTest {

    /**
     * 验证迁移同时创建审批说明、工作流修订号和分享记录所需字段及索引。
     *
     * @throws Exception 迁移文件不可读时抛出
     */
    @Test
    public void migrationShouldCreateWorkflowShareContracts() throws Exception {
        String sql = migrationSql(
                "V34__mysql_workflow_share_and_approval_reason.sql"
        );

        assertTrue(sql.contains("ADD COLUMN `application_reason` VARCHAR(500)"));
        assertTrue(sql.contains("ADD COLUMN `revision` INT NOT NULL DEFAULT 0"));
        assertTrue(sql.contains("CREATE TABLE `tb_workflow_share`"));
        assertTrue(sql.contains("`share_key_hash` VARCHAR(64) NOT NULL"));
        assertTrue(sql.contains("`status`         VARCHAR(32) NOT NULL"));
        assertTrue(sql.contains("`dept_id`        BIGINT UNSIGNED NULL"));
        assertTrue(sql.contains("`modified`       DATETIME NULL"));
        assertTrue(sql.contains("UNIQUE INDEX `uni_workflow_share_key_hash`"));
        assertTrue(sql.contains("INDEX `idx_workflow_share_status` (`workflow_id`, `status`)"));
    }

    /**
     * 验证 V39 为协作分享和对话分享建立用途隔离。
     *
     * @throws Exception 迁移文件不可读时抛出
     */
    @Test
    public void migrationShouldSeparateChatSharePurpose() throws Exception {
        String sql = migrationSql("V39__mysql_workflow_chat_share.sql");

        assertTrue(sql.contains(
                "ADD COLUMN `share_purpose` VARCHAR(32) NOT NULL DEFAULT 'COLLABORATION'"
        ));
        assertTrue(sql.contains("`idx_workflow_share_purpose_status`"));
        assertTrue(sql.contains(
                "(`workflow_id`, `share_purpose`, `status`)"
        ));
    }

    /**
     * 读取工作区中的指定 MySQL 迁移。
     *
     * @param fileName 迁移文件名
     * @return 迁移 SQL
     * @throws Exception 迁移文件不存在或不可读时抛出
     */
    private String migrationSql(String fileName) 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/" + fileName);
            if (Files.isRegularFile(migration)) {
                return Files.readString(migration, StandardCharsets.UTF_8);
            }
            root = root.getParent();
        }
        throw new IllegalStateException("找不到工作流分享迁移: " + fileName);
    }
}
