package ai.decompile.analysis.model.dto;

import ai.decompile.analysis.model.entity.StaticEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public record EnumResponse(UUID id, String name, int width, List<EnumConstResponse> constants) {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static EnumResponse from(StaticEnum e) {
    return new EnumResponse(e.getId(), e.getName(), e.getWidth(), parseConstants(e.getConstants()));
  }

  private static List<EnumConstResponse> parseConstants(String raw) {
    if (Objects.isNull(raw) || raw.isBlank() || "[]".equals(raw.trim())) {
      return Collections.emptyList();
    }

    try {
      var decoded = MAPPER.readValue("\"" + raw + "\"", String.class);
      return MAPPER.readValue(
          decoded,
          MAPPER.getTypeFactory().constructCollectionType(List.class, EnumConstResponse.class));
    } catch (Exception e) {
      return Collections.emptyList();
    }
  }
}
