package com.pharmacopoeia.entity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.*; import lombok.*; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; import java.time.Instant; import java.util.List; import java.util.Map; @Entity @Table(name = "messages") @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Message { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "conversation_id", nullable = false, length = 64) private String conversationId; @Column(name = "user_key", length = 128) private String userKey; @Column(nullable = false, length = 32) private String role; @Column(columnDefinition = "text", nullable = false) private String content; @Column(length = 32) private String intent; @JdbcTypeCode(SqlTypes.JSON) @Column(name = "sources", columnDefinition = "jsonb") private String sources; @JdbcTypeCode(SqlTypes.JSON) @Column(name = "brand_recommendations", columnDefinition = "jsonb") private String brandRecommendations; @Column(length = 32) private String feedback; @Column(name = "created_at") private Instant createdAt; @PrePersist void prePersist() { createdAt = Instant.now(); } @Transient private static final ObjectMapper mapper = new ObjectMapper(); public List> getSourcesList() { if (sources == null || sources.isBlank()) return List.of(); try { return mapper.readValue(sources, new TypeReference>>() {}); } catch (JsonProcessingException e) { return List.of(); } } public void setSourcesList(List> sourcesList) { try { this.sources = sourcesList != null ? mapper.writeValueAsString(sourcesList) : null; } catch (JsonProcessingException e) { this.sources = null; } } public List> getBrandRecommendationsList() { if (brandRecommendations == null || brandRecommendations.isBlank()) return List.of(); try { return mapper.readValue(brandRecommendations, new TypeReference>>() {}); } catch (JsonProcessingException e) { return List.of(); } } public void setBrandRecommendationsList(List> recs) { try { this.brandRecommendations = recs != null ? mapper.writeValueAsString(recs) : null; } catch (JsonProcessingException e) { this.brandRecommendations = null; } } }