package org.raddatz.familienarchiv.person;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.*;

import org.raddatz.familienarchiv.document.DatePrecision;
import org.raddatz.familienarchiv.user.DisplayNameFormatter;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

// prevents infinite recursion in JSON serialization; see ADR-022 for lazy-fetch context
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
@Table(name = "persons")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Person {

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

    @Column(name = "title")
    private String title;

    @Column(nullable = true)
    private String firstName;

    @Column(nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private String lastName;

    @Enumerated(EnumType.STRING)
    @Column(name = "person_type", nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private PersonType personType = PersonType.PERSON;

    // Optional: Aliasse für die Suche (z.B. "Opa Hans")
    private String alias;

    // Optional: Free-text biographical notes
    @Column(columnDefinition = "TEXT")
    private String notes;

    // Most precise birth/death date known. Precision mirrors Document.metaDatePrecision:
    // the date column is nullable, the precision column is NOT NULL with UNKNOWN meaning
    // "no date" — the V76 CHECK constraints enforce (date IS NULL) = (precision = UNKNOWN).
    // DatePrecision is imported cross-domain from document/ by design (ADR-039).
    private LocalDate birthDate;

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

    private LocalDate deathDate;

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

    // Hand-curated generation index from canonical-persons.xlsx (G 0 = oldest).
    // Nullable for persons outside the curated family graph. Drives the
    // Stammbaum strict-rank seed (see #689) and re-import preserves human
    // edits via PersonService.preferHuman (ADR-025).
    @Column(name = "generation")
    private Integer generation;

    @Column(name = "family_member", nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private boolean familyMember = false;

    // The normalizer person_id — join key and re-import idempotency key. Null for manually
    // created persons; unique among non-null values (see ADR-025).
    @Column(name = "source_ref")
    private String sourceRef;

    // A provisional person is one the importer inferred but could not confidently identify.
    // Distinct from familyMember (a genealogical fact); set true only by the importer (Phase 3).
    @Column(name = "provisional", nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private boolean provisional = false;

    // Entity-graph navigation for JPA JOIN queries (e.g. DocumentSpecifications.hasText).
    // Uses entity relationship rather than cross-domain repository access, avoiding a
    // separate DB roundtrip while respecting domain boundaries.
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    @Builder.Default
    private List<PersonNameAlias> nameAliases = new ArrayList<>();

    @Transient
    @Schema(accessMode = Schema.AccessMode.READ_ONLY, requiredMode = Schema.RequiredMode.REQUIRED)
    public String getDisplayName() {
        return DisplayNameFormatter.format(title, firstName, lastName);
    }
}