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;

/**
 * Enterprise dedicated REST endpoints must link to transitions when call-graph resolution
 * proves a concrete machine enum literal on the dispatcher branch.
 */
class EnterpriseDedicatedEndpointLinkingTest {

    private static final String PAY_ENDPOINT = "POST /api/machine/order/pay";

    @Test
    void astExportDedicatedPayEndpointShouldLinkToOrderPayTransition(@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 = findPayEndpointChain(json);

        assertThat(chain.path("triggerPoint").path("event").asText())
                .isEqualTo("click.kamil.enterprise.machines.order.OrderEvent.PAY");
        assertThat(chain.path("matchedTransitions").isArray()).isTrue();
        assertThat(chain.path("matchedTransitions")).isNotEmpty();
        assertThat(chain.path("matchedTransitions").get(0).path("event").asText())
                .isEqualTo("click.kamil.enterprise.machines.order.OrderEvent.PAY");
        assertThat(chain.path("linkResolution").asText()).isEqualTo("RESOLVED");
    }

    private static JsonNode findPayEndpointChain(JsonNode machineJson) {
        for (JsonNode chain : machineJson.path("metadata").path("callChains")) {
            if (PAY_ENDPOINT.equals(chain.path("entryPoint").path("name").asText())) {
                return chain;
            }
        }
        throw new IllegalStateException("pay 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;
    }
}
