package dev.lions.unionflow.server.entity;

import dev.lions.unionflow.server.api.enums.audit.PorteeAudit;
import jakarta.persistence.*;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;

/**
 * Entité pour les logs d'audit
 * Enregistre toutes les actions importantes du système
 *
 * @author UnionFlow Team
 * @version 1.0
 * @since 2025-01-17
 */
@Entity
@Table(name = "audit_logs", indexes = {
    @Index(name = "idx_audit_date_heure", columnList = "date_heure"),
    @Index(name = "idx_audit_utilisateur", columnList = "utilisateur"),
    @Index(name = "idx_audit_module", columnList = "module"),
    @Index(name = "idx_audit_type_action", columnList = "type_action"),
    @Index(name = "idx_audit_severite", columnList = "severite")
})
@Getter
@Setter
public class AuditLog extends BaseEntity {
    
    @Column(name = "type_action", nullable = false, length = 50)
    private String typeAction;
    
    @Column(name = "severite", nullable = false, length = 20)
    private String severite;
    
    @Column(name = "utilisateur", length = 255)
    private String utilisateur;
    
    @Column(name = "role", length = 50)
    private String role;
    
    @Column(name = "module", length = 50)
    private String module;
    
    @Column(name = "description", length = 500)
    private String description;
    
    @Column(name = "details", columnDefinition = "TEXT")
    private String details;
    
    @Column(name = "ip_address", length = 45)
    private String ipAddress;
    
    @Column(name = "user_agent", length = 500)
    private String userAgent;
    
    @Column(name = "session_id", length = 255)
    private String sessionId;
    
    @Column(name = "date_heure", nullable = false)
    private LocalDateTime dateHeure;
    
    @Column(name = "donnees_avant", columnDefinition = "TEXT")
    private String donneesAvant;
    
    @Column(name = "donnees_apres", columnDefinition = "TEXT")
    private String donneesApres;
    
    @Column(name = "entite_id", length = 255)
    private String entiteId;
    
    @Column(name = "entite_type", length = 100)
    private String entiteType;

    /**
     * Organisation concernée par cet événement d'audit.
     * NULL pour les événements de portée PLATEFORME.
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "organisation_id")
    private Organisation organisation;

    /**
     * Portée de visibilité :
     * ORGANISATION = visible par le manager de l'organisation
     * PLATEFORME = visible uniquement par le Super Admin UnionFlow
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "portee", nullable = false, length = 15)
    private PorteeAudit portee = PorteeAudit.PLATEFORME;

    @PrePersist
    protected void onCreate() {
        super.onCreate();
        if (dateHeure == null) {
            dateHeure = LocalDateTime.now();
        }
    }
}

