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

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

/**
 * Directed relationship between two canonical documents.
 */
@Entity
@Table(schema = SchemaNames.DOC, name = "doc_relation", indexes = {
        @Index(name = "idx_doc_relation_parent", columnList = "parent_document_id"),
        @Index(name = "idx_doc_relation_child", columnList = "child_document_id"),
        @Index(name = "idx_doc_relation_type", columnList = "relation_type")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentRelation {

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

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

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

    @Enumerated(EnumType.STRING)
    @Column(name = "relation_type", nullable = false, length = 64)
    private RelationType relationType;

    @Column(name = "sort_order")
    private Integer sortOrder;

    @Column(name = "relation_metadata", columnDefinition = "TEXT")
    private String relationMetadata;

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

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