package org.raddatz.familienarchiv.document.comment;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.raddatz.familienarchiv.document.transcription.MentionDTO;
import org.raddatz.familienarchiv.user.AppUser;

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

@Entity
@Table(name = "document_comments")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentComment {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private UUID id;

    @Column(name = "document_id", nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private UUID documentId;

    @Column(name = "annotation_id")
    private UUID annotationId;

    @Column(name = "block_id")
    private UUID blockId;

    @Column(name = "parent_id")
    private UUID parentId;

    @Column(name = "author_id")
    private UUID authorId;

    @Column(name = "author_name", nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private String authorName;

    @Column(nullable = false, columnDefinition = "TEXT")
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private String content;

    @Column(name = "created_at", nullable = false, updatable = false)
    @CreationTimestamp
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private LocalDateTime createdAt;

    @Column(name = "updated_at", nullable = false)
    @UpdateTimestamp
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private LocalDateTime updatedAt;

    // Populated by the service — not stored in the database
    @Transient
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private List<DocumentComment> replies = new ArrayList<>();

    // JPA join table for structured mention references — not serialized directly
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "comment_mentions",
            joinColumns = @JoinColumn(name = "comment_id"),
            inverseJoinColumns = @JoinColumn(name = "app_user_id")
    )
    @JsonIgnore
    @Builder.Default
    private List<AppUser> mentions = new ArrayList<>();

    // Populated by CommentService before serialization — not persisted.
    @Transient
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private List<MentionDTO> mentionDTOs = new ArrayList<>();
}
