package com.mosquito.project;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@DisplayName("迁移脚本静态语法规则测试")
class MigrationScriptSyntaxTest {

    private static final Path MIGRATION_DIR =
        Path.of("src", "main", "resources", "db", "migration");

    @Test
    @DisplayName("关键迁移脚本不应包含 MySQL 专属方言")
    void keyMigrationsShouldNotContainMysqlSpecificSyntax() throws IOException {
        List<String> files = List.of(
            "V42__Create_system_config_table.sql",
            "V44__Add_approval_timeout_reminder_table.sql",
            "V65__Create_user_permission_table.sql",
            "V74__Create_user_tag_table.sql"
        );

        for (String file : files) {
            String sql = readMigration(file);
            String normalized = sql.toLowerCase();

            assertThat(normalized)
                .doesNotContain("engine=")
                .doesNotContain("auto_increment")
                .doesNotContain("on duplicate key update")
                .doesNotContain(" on update current_timestamp")
                .doesNotContain(" unique key ")
                .doesNotContain(" key idx_")
                .doesNotContain(" comment ");
        }
    }

    @Test
    @DisplayName("V73 必须使用规范化权限列名")
    void v73ShouldUseNormalizedPermissionColumns() throws IOException {
        String sql = readMigration("V73__Add_dashboard_monitor_and_risk_permissions.sql").toLowerCase();
        assertThat(sql)
            .contains("module_code")
            .contains("resource_code")
            .contains("operation_code")
            .doesNotContain(" module, resource, operation");
    }

    @Test
    @DisplayName("V73/V74 角色编码应统一为小写")
    void roleCodesShouldBeLowercase() throws IOException {
        String v73 = readMigration("V73__Add_dashboard_monitor_and_risk_permissions.sql");
        String v74 = readMigration("V74__Create_user_tag_table.sql");
        assertThat(v73).doesNotContain("SUPER_ADMIN").doesNotContain("SYSTEM_ADMIN");
        assertThat(v74).doesNotContain("SUPER_ADMIN").doesNotContain("SYSTEM_ADMIN").doesNotContain("USER_MANAGER");
    }

    private String readMigration(String fileName) throws IOException {
        return Files.readString(MIGRATION_DIR.resolve(fileName), StandardCharsets.UTF_8);
    }
}
