package at.procon.eventhub;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;

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

class MigrationScriptNamingTest {

    private static final Pattern VERSION_PATTERN = Pattern.compile("V([0-9]+)__.*\\.sql");

    @Test
    void versionedFlywayMigrationsUseUniqueVersionNumbers() throws IOException {
        Path migrationDirectory = Path.of("src/main/resources/db/migration");
        Map<String, List<String>> namesByVersion = new TreeMap<>();

        try (var stream = Files.list(migrationDirectory)) {
            stream.filter(path -> path.getFileName().toString().endsWith(".sql"))
                    .map(path -> path.getFileName().toString())
                    .forEach(fileName -> {
                        String version = version(fileName);
                        if (version != null) {
                            namesByVersion.computeIfAbsent(version, ignored -> new ArrayList<>()).add(fileName);
                        }
                    });
        }

        assertThat(namesByVersion)
                .allSatisfy((version, names) -> assertThat(names)
                        .as("Flyway version V%s must be unique", version)
                        .hasSize(1));
    }

    private String version(String fileName) {
        var matcher = VERSION_PATTERN.matcher(fileName);
        return matcher.matches() ? matcher.group(1) : null;
    }
}
