package dev.lions.user.manager.server.impl.repository;

import dev.lions.user.manager.enums.audit.TypeActionAudit;
import dev.lions.user.manager.server.impl.entity.AuditLogEntity;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApplicationScoped
public class AuditLogRepository implements PanacheRepository<AuditLogEntity> {

    public List<AuditLogEntity> search(String realmName,
            String auteurAction,
            LocalDateTime dateDebut,
            LocalDateTime dateFin,
            String typeAction,
            Boolean success,
            int page,
            int pageSize) {

        StringBuilder query = new StringBuilder("1=1");
        Map<String, Object> params = new HashMap<>();

        // Construction dynamique de la requête
        if (realmName != null && !realmName.isEmpty()) {
            query.append(" AND realmName = :realmName");
            params.put("realmName", realmName);
        }
        if (auteurAction != null && !auteurAction.isEmpty()) {
            query.append(" AND auteurAction = :auteurAction");
            params.put("auteurAction", auteurAction);
        }
        if (dateDebut != null) {
            query.append(" AND timestamp >= :dateDebut");
            params.put("dateDebut", dateDebut);
        }
        if (dateFin != null) {
            query.append(" AND timestamp <= :dateFin");
            params.put("dateFin", dateFin);
        }
        if (typeAction != null && !typeAction.isEmpty()) {
            try {
                TypeActionAudit actionEnum = TypeActionAudit.valueOf(typeAction);
                query.append(" AND action = :actionEnum");
                params.put("actionEnum", actionEnum);
            } catch (IllegalArgumentException e) {
                // Ignore invalid enum value filter
            }
        }
        if (success != null) {
            query.append(" AND success = :success");
            params.put("success", success);
        }

        query.append(" ORDER BY timestamp DESC");
        return find(query.toString(), params).page(page, pageSize).list();
    }
}
