import { MOCK_DISCOVER_EVENTS } from '../mock'
import { apiGet } from './api'

function normalizeApiEvent(row) {
  const payload = row.payload || {}
  const data = payload.data || {}
  const level = row.severity ?? data.level ?? payload.level
  return {
    id: row.id,
    source: row.source || 'wazuh',
    event_type: row.event_type,
    domain: row.domain || payload.domain || data.agent || '—',
    severity: level != null ? Number(level) : null,
    summary: data.description || payload.summary || row.event_type,
    agent: data.agent || payload.agent || '—',
    rule_id: data.rule_id || payload.rule_id,
    chamado_public_id: payload.chamado_public_id || null,
    created_at: row.created_at,
    wazuh_link: 'https://wazuh.itecnologys.com/',
  }
}

export async function loadDiscoverEvents() {
  try {
    const data = await apiGet('/api/v1/webhooks/events?source=wazuh')
    const rows = (data.events || []).map(normalizeApiEvent)
    if (rows.length) return { events: rows, fromApi: true }
  } catch {
    /* sem login JWT — mock */
  }
  return { events: MOCK_DISCOVER_EVENTS, fromApi: false }
}
