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;

/**
 * V40 审批发起人部门限制迁移契约测试。
 */
public class ApprovalApplicantDeptRestrictionMigrationContractTest {

    /**
     * 验证迁移以关闭开关兼容历史流程，并提供实例与任务冻结字段。
     *
     * @throws Exception 迁移文件不可读时抛出
     */
    @Test
    public void migrationShouldAddBackwardCompatibleRestrictionFields() throws Exception {
        String sql = migrationSql();

        assertTrue(sql.contains("`restrict_to_applicant_dept` TINYINT NOT NULL DEFAULT 0"));
        assertTrue(sql.contains("`applicant_dept_id` BIGINT UNSIGNED NULL"));
        assertTrue(sql.contains("`applicant_dept_name` VARCHAR(128) NULL"));
        assertTrue(sql.contains("`required_dept_id` BIGINT UNSIGNED NULL"));
        assertTrue(sql.contains("`idx_approval_task_required_dept_status`"));
    }

    /**
     * 读取工作区中的 V40 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/V40__mysql_approval_applicant_dept_restriction.sql");
            if (Files.isRegularFile(migration)) {
                return Files.readString(migration, StandardCharsets.UTF_8);
            }
            root = root.getParent();
        }
        throw new IllegalStateException("找不到 V40 审批发起人部门限制迁移");
    }
}
