package com.unicorn.hgzero.meeting.infra.gateway.entity;

import com.unicorn.hgzero.meeting.biz.domain.MeetingAnalysis;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 회의 분석 결과 Entity
 */
@Entity
@Table(name = "meeting_analysis")
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MeetingAnalysisEntity {

    @Id
    @Column(name = "analysis_id")
    private String analysisId;

    @Column(name = "meeting_id", nullable = false)
    private String meetingId;

    @Column(name = "minutes_id", nullable = false)
    private String minutesId;

    @ElementCollection
    @CollectionTable(name = "meeting_keywords", joinColumns = @JoinColumn(name = "analysis_id"))
    @Column(name = "keyword")
    private List<String> keywords;

    @Column(name = "decisions", columnDefinition = "TEXT")
    private String decisions;

    @Column(name = "agenda_analyses", columnDefinition = "TEXT")
    private String agendaAnalysesJson; // JSON 문자열로 저장

    @Column(name = "status")
    private String status;

    @Column(name = "completed_at")
    private LocalDateTime completedAt;

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    /**
     * Entity를 도메인으로 변환
     */
    public MeetingAnalysis toDomain() {
        List<MeetingAnalysis.AgendaAnalysis> agendaAnalyses = parseAgendaAnalyses();

        return MeetingAnalysis.builder()
                .analysisId(this.analysisId)
                .meetingId(this.meetingId)
                .minutesId(this.minutesId)
                .keywords(this.keywords)
                .decisions(this.decisions)
                .agendaAnalyses(agendaAnalyses)
                .status(this.status)
                .completedAt(this.completedAt)
                .createdAt(this.createdAt)
                .build();
    }

    /**
     * JSON 문자열을 AgendaAnalysis 리스트로 파싱
     */
    private List<MeetingAnalysis.AgendaAnalysis> parseAgendaAnalyses() {
        if (agendaAnalysesJson == null || agendaAnalysesJson.trim().isEmpty() || "{}".equals(agendaAnalysesJson.trim())) {
            return List.of();
        }
        
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(agendaAnalysesJson, new TypeReference<List<MeetingAnalysis.AgendaAnalysis>>() {});
        } catch (Exception e) {
            // JSON 파싱 실패 시 빈 리스트 반환
            return List.of();
        }
    }

    /**
     * 도메인에서 Entity로 변환
     */
    public static MeetingAnalysisEntity fromDomain(MeetingAnalysis domain) {
        String agendaAnalysesJson = convertAgendaAnalysesToJson(domain.getAgendaAnalyses());

        return MeetingAnalysisEntity.builder()
                .analysisId(domain.getAnalysisId())
                .meetingId(domain.getMeetingId())
                .minutesId(domain.getMinutesId())
                .keywords(domain.getKeywords())
                .decisions(domain.getDecisions())
                .agendaAnalysesJson(agendaAnalysesJson)
                .status(domain.getStatus())
                .completedAt(domain.getCompletedAt())
                .createdAt(domain.getCreatedAt())
                .build();
    }

    /**
     * AgendaAnalysis 리스트를 JSON 문자열로 변환
     */
    private static String convertAgendaAnalysesToJson(List<MeetingAnalysis.AgendaAnalysis> agendaAnalyses) {
        if (agendaAnalyses == null || agendaAnalyses.isEmpty()) {
            return "[]";
        }
        
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(agendaAnalyses);
        } catch (Exception e) {
            return "[]";
        }
    }
}