package click.kamil.springstatemachineexporter.analysis.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;

class FlowStepDeserializer extends JsonDeserializer<FlowStep> {

    @Override
    public FlowStep deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        JsonNode node = parser.getCodec().readTree(parser);
        if (node.isTextual()) {
            return FlowStep.builder().event(node.asText()).build();
        }
        return FlowStep.builder()
                .source(textOrNull(node, "source"))
                .event(textOrNull(node, "event"))
                .linkKey(textOrNull(node, "linkKey"))
                .build();
    }

    private static String textOrNull(JsonNode node, String field) {
        JsonNode value = node.get(field);
        if (value == null || value.isNull()) {
            return null;
        }
        String text = value.asText();
        return text.isBlank() ? null : text;
    }
}
