package org.raddatz.familienarchiv.user;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;

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

@Entity
@Table(name = "invite_tokens")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class InviteToken {

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

    @Column(nullable = false, unique = true, length = 10)
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private String code;

    private String label;

    private Integer maxUses;

    @Column(nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private int useCount = 0;

    private String prefillFirstName;
    private String prefillLastName;
    private String prefillEmail;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "invite_token_group_ids", joinColumns = @JoinColumn(name = "invite_token_id"))
    @Column(name = "group_id")
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private Set<UUID> groupIds = new HashSet<>();

    private LocalDateTime expiresAt;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "created_by", nullable = false)
    private AppUser createdBy;

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

    @Column(nullable = false)
    @Builder.Default
    @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
    private boolean revoked = false;

    public boolean isExhausted() {
        return maxUses != null && useCount >= maxUses;
    }

    public boolean isExpired() {
        return expiresAt != null && expiresAt.isBefore(LocalDateTime.now());
    }

    public boolean isActive() {
        return !revoked && !isExhausted() && !isExpired();
    }
}
