package org.raddatz.familienarchiv.document.transcription;

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.BlockSource;

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

@Entity
@Table(name = "transcription_blocks")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TranscriptionBlock {

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

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

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

    @Column(columnDefinition = "TEXT")
    private String text;

    // EAGER: mention set is bounded by block text length (typically < 20 entries).
    // Switching back to LAZY requires callers to be inside an open Hibernate session.
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(
            name = "transcription_block_mentioned_persons",
            joinColumns = @JoinColumn(name = "block_id"))
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    @Builder.Default
    private List<PersonMention> mentionedPersons = new ArrayList<>();

    @Column(length = 200)
    private String label;

    @Column(name = "sort_order", nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private int sortOrder;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 10)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    @Builder.Default
    private BlockSource source = BlockSource.MANUAL;

    @Column(nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    @Builder.Default
    private boolean reviewed = false;

    @Version
    @Column(nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private int version;

    @Column(name = "created_by")
    private UUID createdBy;

    @Column(name = "updated_by")
    private UUID updatedBy;

    @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;
}
