import {
  MOCK_AUDIT_OVERVIEW,
  MOCK_CHAMADOS,
  MOCK_INCIDENTS,
  MOCK_SUMMARY,
} from '../mock'
import { apiGet } from './api'
import { loadDiscoverEvents } from './events'
import { aggregateWazuh24h } from './severity'

export async function loadConsoleHomeData() {
  let fromApi = false
  const result = {
    summary: { ...MOCK_SUMMARY },
    audit: { tenants: [...MOCK_AUDIT_OVERVIEW.tenants] },
    incidents: [...MOCK_INCIDENTS],
    chamados: [...MOCK_CHAMADOS],
    alertCounts: { critical: 0, high: 0, medium: 0, low: 0 },
    fromApi: false,
  }

  const { events, fromApi: eventsApi } = await loadDiscoverEvents()
  result.alertCounts = aggregateWazuh24h(events)
  if (eventsApi) fromApi = true

  try {
    const summary = await apiGet('/api/v1/desk/summary')
    if (summary) {
      result.summary = summary
      if (summary.recent_tickets?.length) {
        result.chamados = summary.recent_tickets.map((t) => ({
          public_id: t.chamado_public_id || `TK-${t.id}`,
          status: t.status,
          domain: t.domain || '—',
          max_severity: t.severity,
        }))
      }
      fromApi = true
    }
  } catch { /* mock */ }

  try {
    const audit = await apiGet('/api/v1/audit/overview')
    if (audit?.tenants?.length) {
      result.audit = audit
      fromApi = true
    }
  } catch { /* mock */ }

  try {
    const inc = await apiGet('/api/v1/agents/incidents?status=open&limit=8')
    if (inc?.incidents?.length) {
      result.incidents = inc.incidents
      fromApi = true
    }
  } catch { /* mock */ }

  result.fromApi = fromApi
  return result
}

/** Flatten top_issues from all audit tenants for domain attention list */
export function collectDomainAttention(tenants, limit = 12) {
  const rows = []
  for (const t of tenants || []) {
    for (const issue of t.top_issues || []) {
      rows.push({
        tenant_id: t.tenant_id,
        tenant_name: t.name,
        domain: issue.domain,
        check_id: issue.check_id,
        message: issue.message || issue.status,
        status: issue.status,
      })
    }
  }
  return rows.slice(0, limit)
}
