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

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

import java.util.ArrayList;
import java.util.List;

/**
 * 안건별 회의록 섹션 Entity
 * PostgreSQL JSON 컬럼을 사용하여 구조화된 데이터 저장
 */
@Entity
@Table(name = "agenda_sections")
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AgendaSectionEntity extends BaseTimeEntity {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Id
    @Column(name = "id", length = 36)
    private String id;

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

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

    @Column(name = "agenda_number", nullable = false)
    private Integer agendaNumber;

    @Column(name = "agenda_title", length = 200, nullable = false)
    private String agendaTitle;

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

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

    @Column(name = "pending_items", columnDefinition = "json")
    private String pendingItemsJson;

    @Column(name = "todos", columnDefinition = "json")
    private String todosJson;

    /**
     * Domain 객체로 변환
     */
    public AgendaSection toDomain() {
        return AgendaSection.builder()
                .id(this.id)
                .minutesId(this.minutesId)
                .meetingId(this.meetingId)
                .agendaNumber(this.agendaNumber)
                .agendaTitle(this.agendaTitle)
                .aiSummaryShort(this.aiSummaryShort)
                .summary(this.summary)
                .pendingItems(parseJsonToList(this.pendingItemsJson, new TypeReference<List<String>>() {}))
                .todos(parseJsonToList(this.todosJson, new TypeReference<List<AgendaSection.TodoItem>>() {}))
                .createdAt(this.getCreatedAt())
                .updatedAt(this.getUpdatedAt())
                .build();
    }

    /**
     * Domain 객체에서 Entity 생성
     */
    public static AgendaSectionEntity fromDomain(AgendaSection section) {
        return AgendaSectionEntity.builder()
                .id(section.getId())
                .minutesId(section.getMinutesId())
                .meetingId(section.getMeetingId())
                .agendaNumber(section.getAgendaNumber())
                .agendaTitle(section.getAgendaTitle())
                .aiSummaryShort(section.getAiSummaryShort())
                .summary(section.getSummary())
                .pendingItemsJson(toJson(section.getPendingItems()))
                .todosJson(toJson(section.getTodos()))
                .build();
    }

    /**
     * 객체를 JSON 문자열로 변환
     */
    private static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 변환 실패", e);
        }
    }

    /**
     * JSON 문자열을 리스트로 변환
     */
    private static <T> List<T> parseJsonToList(String json, TypeReference<List<T>> typeReference) {
        if (json == null || json.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 파싱 실패", e);
        }
    }
}
