package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.exporter.JsonExporter;
import click.kamil.springstatemachineexporter.service.ExportService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

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

class EnterpriseOrderCanonicalExportTest {

    @Test
    void shouldExportEnterpriseOrderMachineWithPackageCanonicalIdentifiers(@TempDir Path tempDir) throws Exception {
        Path enterprise = findProjectRoot().resolve("state_machines/state_machine_enterprise");
        ExportService exportService = new ExportService(List.of(new JsonExporter()));
        exportService.runExporter(enterprise, tempDir, List.of("json"), true, List.of(), null, null,
                click.kamil.springstatemachineexporter.exporter.EnumFormat.fn,
                click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);

        JsonNode machine = readMachineJson(tempDir, "OrderStateMachineConfiguration", new ObjectMapper());
        JsonNode firstTransition = machine.path("transitions").get(0);

        assertThat(firstTransition.path("event").path("fullIdentifier").asText())
                .isEqualTo("click.kamil.enterprise.machines.order.OrderEvent.PAY");
        assertThat(firstTransition.path("sourceStates").get(0).path("fullIdentifier").asText())
                .isEqualTo("click.kamil.enterprise.machines.order.OrderState.NEW");
        assertThat(machine.path("startStates").get(0).asText())
                .isEqualTo("click.kamil.enterprise.machines.order.OrderState.NEW");
    }

    private static JsonNode readMachineJson(Path outputDir, String configBaseName, ObjectMapper mapper)
            throws Exception {
        Path machineDir;
        try (var stream = Files.list(outputDir)) {
            machineDir = stream
                    .filter(Files::isDirectory)
                    .filter(path -> path.getFileName().toString().endsWith(configBaseName))
                    .findFirst()
                    .orElseThrow(() -> new IllegalStateException("No output for " + configBaseName));
        }
        return mapper.readTree(machineDir.resolve(machineDir.getFileName() + ".json").toFile());
    }

    private static Path findProjectRoot() {
        Path current = Path.of(".").toAbsolutePath();
        while (current != null && !Files.exists(current.resolve("settings.gradle"))) {
            current = current.getParent();
        }
        return current;
    }
}
