/** Custom serializer for sealed interface with unwrapped variants. Emits the discriminator tag alongside the inner record's fields (flat object). */
class {{ class_name }}Serializer extends StdSerializer<{{ class_name }}> {
  private static final long serialVersionUID = 1L;
  /** ObjectMapper for serializing inner variant values. */
  private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER =
      new com.fasterxml.jackson.databind.ObjectMapper()
          .registerModule(new com.fasterxml.jackson.datatype.jdk8.Jdk8Module())
          .setPropertyNamingStrategy(
              com.fasterxml.jackson.databind.PropertyNamingStrategies.SNAKE_CASE)
          .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);

  /** Creates a new {{ class_name }}Serializer. */
  {{ class_name }}Serializer() {
    super({{ class_name }}.class);
  }

  @Override
  @SuppressWarnings("PMD.CyclomaticComplexity")
  public void serialize({{ class_name }} value, JsonGenerator gen, SerializerProvider provider)
      throws java.io.IOException {
    String tag;
    Object inner;
    {%- for variant in variants %}
    {% if loop.index0 > 0 %}else {% endif %}if (value instanceof {{ class_name }}.{{ variant.name }} variant{{ variant.name }}) {
      tag = "{{ variant.discriminator }}";
      {%- if variant.is_unit %}
      inner = null;
      {%- elif variant.is_tuple %}
      inner = variant{{ variant.name }}.value();
      {%- else %}
      inner = variant{{ variant.name }};
      {%- endif %}
    }
    {%- endfor %}
    else {
      throw new com.fasterxml.jackson.databind.JsonMappingException(
          gen, "Unknown {{ class_name }} variant: " + value.getClass().getName());
    }

    gen.writeStartObject();
    gen.writeStringField("{{ tag_field }}", tag);
    if (inner != null) {
      com.fasterxml.jackson.databind.JsonNode tree = MAPPER.valueToTree(inner);
      if (tree.isObject()) {
        java.util.Iterator<java.util.Map.Entry<String, com.fasterxml.jackson.databind.JsonNode>>
            fieldIterator = tree.fields();
        while (fieldIterator.hasNext()) {
          java.util.Map.Entry<String, com.fasterxml.jackson.databind.JsonNode> field =
              fieldIterator.next();
          gen.writeFieldName(field.getKey());
          gen.writeTree(field.getValue());
        }
      }
    }
    gen.writeEndObject();
  }
}
