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;

    @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<Map<String, Object>> getSourcesList() {
        if (sources == null || sources.isBlank()) return List.of();
        try {
            return mapper.readValue(sources, new TypeReference<List<Map<String, Object>>>() {});
        } catch (JsonProcessingException e) {
            return List.of();
        }
    }

    public void setSourcesList(List<Map<String, Object>> sourcesList) {
        try {
            this.sources = sourcesList != null ? mapper.writeValueAsString(sourcesList) : null;
        } catch (JsonProcessingException e) {
            this.sources = null;
        }
    }
}
