package dev.lions.unionflow.server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * Délégation temporaire d'un rôle.
 *
 * <p>Cas d'usage : trésorier en congé délègue son rôle au trésorier adjoint pour 2 semaines.
 *
 * <p>Le {@code PermissionChecker} consulte cette table pour calculer le rôle effectif :
 * <strong>roles directs ∪ roles délégués actifs</strong> (statut=ACTIVE et dateFin > now).
 *
 * @since 2026-04-25 (P1-NEW-5)
 */
@Entity
@Table(name = "role_delegations", indexes = {
    @Index(name = "idx_delegation_org", columnList = "organisation_id"),
    @Index(name = "idx_delegation_delegataire", columnList = "delegataire_user_id")
})
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = true)
public class RoleDelegation extends BaseEntity {

  @NotNull
  @Column(name = "organisation_id", nullable = false)
  private UUID organisationId;

  @NotNull
  @Column(name = "delegant_user_id", nullable = false)
  private UUID delegantUserId;

  @NotNull
  @Column(name = "delegataire_user_id", nullable = false)
  private UUID delegataireUserId;

  @NotBlank
  @Column(name = "role_delegue", nullable = false, length = 50)
  private String roleDelegue;

  @NotNull
  @Column(name = "date_debut", nullable = false)
  private LocalDateTime dateDebut;

  @NotNull
  @Column(name = "date_fin", nullable = false)
  private LocalDateTime dateFin;

  @Column(name = "motif", length = 500)
  private String motif;

  @NotBlank
  @Column(name = "statut", nullable = false, length = 20)
  @Builder.Default
  private String statut = "ACTIVE"; // ACTIVE, EXPIREE, REVOQUEE

  @Column(name = "date_revocation")
  private LocalDateTime dateRevocation;

  /** Vrai si la délégation est active à l'instant donné. */
  public boolean isActiveAt(LocalDateTime instant) {
    return "ACTIVE".equals(statut)
        && dateDebut != null && !dateDebut.isAfter(instant)
        && dateFin != null && dateFin.isAfter(instant);
  }
}
