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

import com.unicorn.hgzero.common.entity.BaseTimeEntity;
import com.unicorn.hgzero.meeting.biz.domain.Minutes;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 회의록 Entity
 */
@Entity
@Table(name = "minutes")
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MinutesEntity extends BaseTimeEntity {

    @Id
    @Column(name = "minutes_id", length = 50)
    private String minutesId;

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

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

    @OneToMany(mappedBy = "minutes", cascade = CascadeType.ALL, orphanRemoval = true)
    @Builder.Default
    private List<MinutesSectionEntity> sections = new ArrayList<>();

    @Column(name = "status", length = 20, nullable = false)
    @Builder.Default
    private String status = "DRAFT";

    @Column(name = "version", nullable = false)
    @Builder.Default
    private Integer version = 1;

    @Column(name = "created_by", length = 50, nullable = false)
    private String createdBy;

    @Column(name = "finalized_by", length = 50)
    private String finalizedBy;

    @Column(name = "finalized_at")
    private LocalDateTime finalizedAt;

    public Minutes toDomain() {
        return Minutes.builder()
                .minutesId(this.minutesId)
                .meetingId(this.meetingId)
                .title(this.title)
                .sections(this.sections.stream()
                        .map(MinutesSectionEntity::toDomain)
                        .collect(Collectors.toList()))
                .status(this.status)
                .version(this.version)
                .createdBy(this.createdBy)
                .finalizedBy(this.finalizedBy)
                .finalizedAt(this.finalizedAt)
                .build();
    }

    public static MinutesEntity fromDomain(Minutes minutes) {
        return MinutesEntity.builder()
                .minutesId(minutes.getMinutesId())
                .meetingId(minutes.getMeetingId())
                .title(minutes.getTitle())
                .status(minutes.getStatus())
                .version(minutes.getVersion())
                .createdBy(minutes.getCreatedBy())
                .finalizedBy(minutes.getFinalizedBy())
                .finalizedAt(minutes.getFinalizedAt())
                .build();
    }

    public void finalize(String userId) {
        this.status = "FINALIZED";
        this.finalizedBy = userId;
        this.finalizedAt = LocalDateTime.now();
    }

    public void updateVersion() {
        this.version++;
    }
}
