package at.procon.dip.clustering.entity;

import at.procon.dip.architecture.SchemaNames;
import at.procon.dip.domain.document.entity.Document;
import at.procon.dip.domain.document.entity.DocumentEmbedding;
import at.procon.dip.domain.document.entity.DocumentTextRepresentation;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
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;

@Entity
@Table(schema = SchemaNames.DOC, name = "doc_embedding_cluster_assignment", indexes = {
        @Index(name = "idx_doc_cluster_assignment_run_jpa", columnList = "cluster_run_id"),
        @Index(name = "idx_doc_cluster_assignment_cluster_jpa", columnList = "cluster_id"),
        @Index(name = "idx_doc_cluster_assignment_document_jpa", columnList = "cluster_run_id, document_id")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class EmbeddingClusterAssignment {

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

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "cluster_run_id", nullable = false)
    private EmbeddingClusterRun clusterRun;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cluster_id")
    private EmbeddingCluster cluster;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "embedding_id", nullable = false)
    private DocumentEmbedding embedding;

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

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "representation_id", nullable = false)
    private DocumentTextRepresentation representation;

    @Column(name = "cluster_label_raw", nullable = false)
    private Integer clusterLabelRaw;

    @Column(name = "membership_score")
    private Double membershipScore;

    @Column(name = "distance_to_centroid")
    private Double distanceToCentroid;

    @Builder.Default
    @Column(name = "is_noise", nullable = false)
    private boolean noise = false;

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

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