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;

/**
 * V32 审批实例租户迁移契约测试。
 */
public class ApprovalInstanceTenantMigrationContractTest {

    /**
     * 验证历史实例从申请人账号回填租户，且空租户会阻断迁移。
     *
     * @throws Exception 迁移文件不可读时抛出
     */
    @Test
    public void migrationShouldBackfillAndGuardApprovalTenant() throws Exception {
        String sql = migrationSql();

        assertTrue(sql.contains("ADD COLUMN `tenant_id` BIGINT UNSIGNED NULL"));
        assertTrue(sql.contains("LEFT JOIN `tb_sys_account` applicant ON applicant.`id` = approval.`applicant_id`"));
        assertTrue(sql.contains("applicant.`id` IS NULL OR applicant.`tenant_id` IS NULL"));
        assertTrue(sql.contains("JOIN `tb_sys_account` applicant ON applicant.`id` = approval.`applicant_id`"));
        assertTrue(sql.contains("SET approval.`tenant_id` = applicant.`tenant_id`"));
        assertTrue(sql.contains("tmp_approval_instance_tenant_guard"));
        assertTrue(sql.indexOf("tmp_approval_instance_tenant_guard") < sql.indexOf("ADD COLUMN `tenant_id`"));
        assertTrue(sql.contains("MODIFY COLUMN `tenant_id` BIGINT UNSIGNED NOT NULL"));
        assertTrue(sql.contains("`tenant_id`, `status`, `submitted_at`"));
    }

    /**
     * 读取工作区中的 V32 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/V32__mysql_approval_instance_tenant.sql");
            if (Files.isRegularFile(migration)) {
                return Files.readString(migration, StandardCharsets.UTF_8);
            }
            root = root.getParent();
        }
        throw new IllegalStateException("找不到 V32 审批实例租户迁移");
    }
}
