package ai.decompile.analysis.model.dto;

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

public record StructResponse(
    UUID id, String name, int size, boolean isUnion, List<StructMemberResponse> members) {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static StructResponse from(StaticStruct s) {
    return new StructResponse(
        s.getId(), s.getName(), s.getSize(), s.isUnion(), parseMembers(s.getMembers()));
  }

  private static List<StructMemberResponse> parseMembers(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, StructMemberResponse.class));
    } catch (Exception e) {
      return Collections.emptyList();
    }
  }
}
