package click.kamil.springstatemachineexporter.service;

import click.kamil.springstatemachineexporter.analysis.model.AnalysisResult;
import click.kamil.springstatemachineexporter.model.StateMachineModel;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

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

class JsonImportServiceTest {

    @Test
    void shouldImportFromJson(@TempDir Path tempDir) throws IOException {
        Path jsonFile = tempDir.resolve("test.json");
        String json = """
                {
                  "name" : "ImportedSM",
                  "transitions" : [ {
                    "type" : "EXTERNAL",
                    "sourceStates" : [ { "rawName" : "S1", "fullIdentifier" : "S1" } ],
                    "targetStates" : [ { "rawName" : "S2", "fullIdentifier" : "S2" } ],
                    "event" : { "rawName" : "E1", "fullIdentifier" : "E1" }
                  } ],
                  "startStates" : [ "S1" ],
                  "endStates" : [ "S2" ]
                }
                """;
        Files.writeString(jsonFile, json);

        JsonImportService importService = new JsonImportService();
        StateMachineModel model = importService.importJson(jsonFile);

        assertThat(model.getName()).isEqualTo("ImportedSM");
        assertThat(model.getTransitions()).hasSize(1);
        assertThat(model.getTransitions().get(0).getEvent().rawName()).isEqualTo("E1");
        assertThat(model.getStartStates()).containsExactly("S1");
        assertThat(model.getEndStates()).containsExactly("S2");
    }

    @Test
    void shouldImportRichAnalysisResultFromJson(@TempDir Path tempDir) throws IOException {
        Path jsonFile = tempDir.resolve("rich.json");
        String json = """
                {
                  "name" : "RichSM",
                  "transitions" : [],
                  "startStates" : [],
                  "endStates" : [],
                  "metadata" : {
                    "entryPoints" : [ {
                        "type" : "REST",
                        "name" : "POST /rich",
                        "className" : "RichController",
                        "methodName" : "submit"
                    } ]
                  }
                }
                """;
        Files.writeString(jsonFile, json);

        JsonImportService importService = new JsonImportService();
        AnalysisResult result = importService.importAnalysisResult(jsonFile);

        assertThat(result.getName()).isEqualTo("RichSM");
        assertThat(result.getMetadata().getEntryPoints()).hasSize(1);
        assertThat(result.getMetadata().getEntryPoints().get(0).getName()).isEqualTo("POST /rich");
    }
}
