/** Buckets Wazuh — mesma escala da home Console */

export const SEVERITY_BUCKETS = [
  { key: 'critical', label: 'Critical severity', hint: 'Rule level 15 or higher', className: 'wz-sev-critical', min: 15, max: 99 },
  { key: 'high', label: 'High severity', hint: 'Rule level 12 to 14', className: 'wz-sev-high', min: 12, max: 14 },
  { key: 'medium', label: 'Medium severity', hint: 'Rule level 7 to 11', className: 'wz-sev-med', min: 7, max: 11 },
  { key: 'low', label: 'Low severity', hint: 'Rule level 0 to 6', className: 'wz-sev-low', min: 0, max: 6 },
]

export function bucketForLevel(level) {
  const n = Number(level)
  if (Number.isNaN(n)) return null
  return SEVERITY_BUCKETS.find((b) => n >= b.min && n <= b.max)?.key ?? null
}

export function aggregateWazuh24h(events) {
  const counts = Object.fromEntries(SEVERITY_BUCKETS.map((b) => [b.key, 0]))
  const now = Date.now()
  const windowMs = 24 * 60 * 60 * 1000
  for (const ev of events || []) {
    if (ev.source !== 'wazuh') continue
    const ts = ev.created_at ? new Date(ev.created_at).getTime() : now
    if (now - ts > windowMs) continue
    const bucket = bucketForLevel(ev.severity)
    if (bucket) counts[bucket] += 1
  }
  return counts
}

export function filterByBucket(events, bucketKey) {
  if (!bucketKey) return events
  const now = Date.now()
  const windowMs = 24 * 60 * 60 * 1000
  return (events || []).filter((ev) => {
    if (bucketForLevel(ev.severity) !== bucketKey) return false
    if (ev.source !== 'wazuh') return false
    const ts = ev.created_at ? new Date(ev.created_at).getTime() : now
    return now - ts <= windowMs
  })
}

export function bucketLabel(bucketKey) {
  return SEVERITY_BUCKETS.find((b) => b.key === bucketKey)?.label ?? bucketKey
}
