package click.kamil.springstatemachineexporter.analysis.model;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

class FlowStepSerializer extends JsonSerializer<FlowStep> {

    @Override
    public void serialize(FlowStep step, JsonGenerator generator, SerializerProvider serializers) throws IOException {
        if (step == null) {
            generator.writeNull();
            return;
        }
        boolean structured = step.getSource() != null && !step.getSource().isBlank()
                || step.getLinkKey() != null && !step.getLinkKey().isBlank();
        if (!structured && step.getEvent() != null && !step.getEvent().isBlank()) {
            generator.writeString(step.getEvent());
            return;
        }
        generator.writeStartObject();
        if (step.getSource() != null && !step.getSource().isBlank()) {
            generator.writeStringField("source", step.getSource());
        }
        if (step.getEvent() != null && !step.getEvent().isBlank()) {
            generator.writeStringField("event", step.getEvent());
        }
        if (step.getLinkKey() != null && !step.getLinkKey().isBlank()) {
            generator.writeStringField("linkKey", step.getLinkKey());
        }
        generator.writeEndObject();
    }
}
