package com.gnx.telemedicine.model;

import com.gnx.telemedicine.model.enums.DuplicateStatus;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

@Getter
@Setter
@Entity
@Table(name = "duplicate_patient_records")
public class DuplicatePatientRecord {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Column(name = "id")
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "primary_patient_id", nullable = false)
    private Patient primaryPatient;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "duplicate_patient_id", nullable = false)
    private Patient duplicatePatient;

    @Column(name = "match_score", nullable = false, precision = 5, scale = 2)
    private BigDecimal matchScore; // 0-100

    @OneToMany(mappedBy = "duplicateRecord", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DuplicateMatchReason> matchReasons;

    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    private DuplicateStatus status = DuplicateStatus.PENDING;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reviewed_by")
    private UserModel reviewedBy;

    @Column(name = "reviewed_at")
    private Instant reviewedAt;

    @Column(name = "review_notes", columnDefinition = "TEXT")
    private String reviewNotes;

    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private Instant createdAt = Instant.now();

    @PrePersist
    @PreUpdate
    private void ensureUniquePatients() {
        if (primaryPatient != null && duplicatePatient != null && 
            primaryPatient.getId().equals(duplicatePatient.getId())) {
            throw new IllegalArgumentException("Primary and duplicate patient cannot be the same");
        }
    }
}

