package com.cameleer.server.app.alerting.dto;

import com.cameleer.server.core.alerting.AlertSeverity;

import java.util.EnumMap;
import java.util.Map;

/**
 * Response shape for {@code GET /alerts/unread-count}.
 * <p>
 * {@code total} is the sum of {@code bySeverity} values. The UI branches bell colour on
 * the highest severity present, so callers can inspect the map directly.
 */
public record UnreadCountResponse(long total, Map<AlertSeverity, Long> bySeverity) {

    public UnreadCountResponse {
        // Defensive copy + fill in missing severities as 0 so the UI never sees null/undefined.
        EnumMap<AlertSeverity, Long> normalized = new EnumMap<>(AlertSeverity.class);
        for (AlertSeverity s : AlertSeverity.values()) normalized.put(s, 0L);
        if (bySeverity != null) bySeverity.forEach((k, v) -> normalized.put(k, v == null ? 0L : v));
        bySeverity = Map.copyOf(normalized);
    }

    public static UnreadCountResponse from(Map<AlertSeverity, Long> counts) {
        long total = counts == null ? 0L
                : counts.values().stream().filter(v -> v != null).mapToLong(Long::longValue).sum();
        return new UnreadCountResponse(total, counts == null ? Map.of() : counts);
    }
}
