package org.raddatz.familienarchiv.person;

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

import org.raddatz.familienarchiv.user.DisplayNameFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@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;

    private Integer birthYear;
    private Integer deathYear;

    @Column(name = "family_member", nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private boolean familyMember = 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);
    }
}