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;

/**
 * Regression for REST dispatcher chains: JSON round-trip must not re-infer all transition events
 * for generic {@code {event}} endpoints.
 */
class EnterpriseDispatcherMatchedTransitionsRegressionTest {

    private static final String TRANSITION_ENDPOINT = "POST /api/machine/{machineType}/transition/{event}";

    @Test
    void astExportGenericTransitionEndpointShouldRemainUnlinked(@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 json = readMachineJson(tempDir, "OrderStateMachineConfiguration", new ObjectMapper());
        JsonNode chain = findTransitionEndpointChain(json);

        assertThat(chain.path("triggerPoint").path("external").asBoolean()).isTrue();
        assertThat(chain.path("triggerPoint").path("polymorphicEvents").isArray()).isTrue();
        assertThat(chain.path("triggerPoint").path("polymorphicEvents")).isEmpty();
        JsonNode matched = chain.path("matchedTransitions");
        assertThat(matched.isNull() || (matched.isArray() && matched.isEmpty())).isTrue();
        assertThat(chain.path("linkResolution").asText()).isEqualTo("UNRESOLVED_EXTERNAL");
    }

    private static JsonNode findTransitionEndpointChain(JsonNode machineJson) {
        for (JsonNode chain : machineJson.path("metadata").path("callChains")) {
            String name = chain.path("entryPoint").path("name").asText();
            if (TRANSITION_ENDPOINT.equals(name)
                    || (name.contains("/transition/{event}") && name.contains("POST /api/machine/"))) {
                return chain;
            }
        }
        throw new IllegalStateException("transition endpoint chain not found");
    }

    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;
    }
}
