package org.raddatz.familienarchiv.person.relationship;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.person.Person;

import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;

@Entity
@Table(name = "person_relationships")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString(exclude = "notes")
public class PersonRelationship {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "person_id", nullable = false)
    @JsonIgnore
    private Person person;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "related_person_id", nullable = false)
    @JsonIgnore
    private Person relatedPerson;

    @Enumerated(EnumType.STRING)
    @Column(name = "relation_type", nullable = false, length = 30)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private RelationType relationType;

    // Start/end of the relationship (wedding, employment start, …). The date column
    // is nullable, the precision column is NOT NULL with UNKNOWN meaning "no date" —
    // the V78 CHECK constraints enforce (date IS NULL) = (precision = UNKNOWN) and
    // from_date <= to_date. Mirrors Person.{birth,death}Date (ADR-039 / ADR-044).
    private LocalDate fromDate;

    @Enumerated(EnumType.STRING)
    @Column(name = "from_date_precision", nullable = false, length = 16)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private DatePrecision fromDatePrecision = DatePrecision.UNKNOWN;

    private LocalDate toDate;

    @Enumerated(EnumType.STRING)
    @Column(name = "to_date_precision", nullable = false, length = 16)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private DatePrecision toDatePrecision = DatePrecision.UNKNOWN;

    @Column(length = 2000)
    private String notes;

    @CreationTimestamp
    @Column(name = "created_at", updatable = false, nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private Instant createdAt;
}
