package org.raddatz.familienarchiv.geschichte;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.raddatz.familienarchiv.geschichte.journeyitem.JourneyItem;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.person.Person;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Entity
@Table(name = "geschichten")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Geschichte {

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

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

    @Column(columnDefinition = "TEXT")
    private String body;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    @Builder.Default
    private GeschichteStatus status = GeschichteStatus.DRAFT;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    @Builder.Default
    private GeschichteType type = GeschichteType.STORY;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private AppUser author;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "geschichten_persons",
            joinColumns = @JoinColumn(name = "geschichte_id"),
            inverseJoinColumns = @JoinColumn(name = "person_id"))
    @Builder.Default
    private Set<Person> persons = new HashSet<>();

    // LAZY per docs/adr/022-eager-to-lazy-fetch-strategy.md. open-in-view is FALSE
    // (application.yaml), so this collection is DEAD at Jackson serialization time unless
    // explicitly initialized inside the service transaction. getById() is
    // @Transactional(readOnly=true) AND calls getItems().size() to force-init before return.
    // list() must NOT serialize items at all — it returns a GeschichteSummary projection.
    // This is the first List ("bag") collection on Geschichte — adding a second EAGER/
    // fetch-joined List here will throw MultipleBagFetchException at boot.
    @OneToMany(mappedBy = "geschichte", cascade = CascadeType.ALL, orphanRemoval = true,
               fetch = FetchType.LAZY)
    @OrderBy("position ASC")
    @Builder.Default
    private List<JourneyItem> items = new ArrayList<>();

    @CreationTimestamp
    @Column(updatable = false)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private LocalDateTime updatedAt;

    @Column(name = "published_at")
    private LocalDateTime publishedAt;
}
