import { formatDurationMs } from '@overdeck/deck-ui'
import type { ActivityEvent } from '../../lib/activity-types'

function add(rows: Array<{ label: string; value: string }>, label: string, value: unknown) {
  if (value === undefined || value === null) return
  rows.push({ label, value: typeof value === 'number' ? value.toLocaleString() : String(value) })
}

function flatten(rows: Array<{ label: string; value: string }>, prefix: string, value: unknown) {
  if (value === undefined || value === null) return
  if (Array.isArray(value)) return value.forEach((entry, index) => flatten(rows, `${prefix}[${index}]`, entry))
  if (typeof value !== 'object') return add(rows, prefix, value)
  for (const [key, child] of Object.entries(value)) flatten(rows, `${prefix}.${key}`, child)
}

export function activityDetailRows(event: ActivityEvent): Array<{ label: string; value: string }> {
  const rows: Array<{ label: string; value: string }> = []
  for (const [label, value] of Object.entries({ id: event.id, time: event.ts, category: event.category, source: event.source, actor: event.actor, severity: event.severity, title: event.title, lifecycle: event.lifecycle, result: event.result, project: event.project, host: event.host, runtime: event.runtime, session: event.session, account: event.account, duration: event.durationMs === undefined ? undefined : formatDurationMs(event.durationMs), rc: event.rc, dedupeKey: event.dedupeKey })) add(rows, label, value)
  if (event.correlation !== undefined) flatten(rows, 'correlation', event.correlation)
  if (event.evidence !== undefined) flatten(rows, 'evidence', event.evidence)
  if (event.detail !== undefined) flatten(rows, 'detail', event.detail)
  return rows
}
