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

import at.procon.dip.architecture.SchemaNames;
import at.procon.dip.domain.document.SourceType;
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.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;

/**
 * Provenance row for a canonical document.
 */
@Entity
@Table(schema = SchemaNames.DOC, name = "doc_source", indexes = {
        @Index(name = "idx_doc_source_document", columnList = "document_id"),
        @Index(name = "idx_doc_source_type", columnList = "source_type"),
        @Index(name = "idx_doc_source_external_id", columnList = "external_source_id"),
        @Index(name = "idx_doc_source_received_at", columnList = "received_at"),
        @Index(name = "idx_doc_source_parent_source", columnList = "parent_source_id")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentSource {

    @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 = "source_type", nullable = false, length = 64)
    private SourceType sourceType;

    @Column(name = "external_source_id", length = 500)
    private String externalSourceId;

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

    @Column(name = "source_filename", length = 1000)
    private String sourceFilename;

    @Column(name = "parent_source_id")
    private UUID parentSourceId;

    @Column(name = "import_batch_id", length = 255)
    private String importBatchId;

    @Column(name = "received_at")
    private OffsetDateTime receivedAt;

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

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