package at.procon.dip.domain.document.entity;

import at.procon.dip.architecture.SchemaNames;
import at.procon.dip.domain.document.ContentRole;
import at.procon.dip.domain.document.StorageType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.Lob;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.Table;
import java.time.OffsetDateTime;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Stored payload variant for a canonical document.
 */
@Entity
@Table(schema = SchemaNames.DOC, name = "doc_content", indexes = {
        @Index(name = "idx_doc_content_document", columnList = "document_id"),
        @Index(name = "idx_doc_content_role", columnList = "content_role"),
        @Index(name = "idx_doc_content_hash", columnList = "content_hash"),
        @Index(name = "idx_doc_content_storage_type", columnList = "storage_type")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentContent {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "document_id", nullable = false)
    private Document document;

    @Enumerated(EnumType.STRING)
    @Column(name = "content_role", nullable = false, length = 64)
    private ContentRole contentRole;

    @Enumerated(EnumType.STRING)
    @Column(name = "storage_type", nullable = false, length = 64)
    private StorageType storageType;

    @Column(name = "mime_type", length = 255)
    private String mimeType;

    @Column(name = "charset_name", length = 120)
    private String charsetName;

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

    @Lob
    @Column(name = "binary_content")
    private byte[] binaryContent;

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

    @Column(name = "content_hash", length = 64)
    private String contentHash;

    @Column(name = "size_bytes")
    private Long sizeBytes;

    @Builder.Default
    @Column(name = "created_at", nullable = false, updatable = false)
    private OffsetDateTime createdAt = OffsetDateTime.now();

    @PrePersist
    protected void onCreate() {
        createdAt = OffsetDateTime.now();
    }
}
