import type { SearchResult } from '../design-system/composites/CommandPalette/types'
import { exchanges, type Exchange } from './exchanges'
import { routes } from './routes'
import { agents } from './agents'
import { SIDEBAR_APPS, buildRouteToAppMap, type SidebarApp } from './sidebar'
import { formatDuration, statusLabel, statusToVariant, formatTimestamp } from '../utils/format-utils'

function healthToColor(health: SidebarApp['health']): string {
  switch (health) {
    case 'live': return 'success'
    case 'stale': return 'warning'
    case 'dead': return 'error'
  }
}

export function buildSearchData(
  exs: Exchange[] = exchanges,
  rts: typeof routes = routes,
  ags: typeof agents = agents,
  apps: SidebarApp[] = SIDEBAR_APPS,
): SearchResult[] {
  const results: SearchResult[] = []

  for (const app of apps) {
    const liveAgents = app.agents.filter((a) => a.status === 'live').length
    results.push({
      id: app.id,
      category: 'application',
      title: app.name,
      badges: [{ label: app.health.toUpperCase(), color: healthToColor(app.health) }],
      meta: `${app.routes.length} routes · ${app.agents.length} agents (${liveAgents} live) · ${app.exchangeCount.toLocaleString()} exchanges`,
      path: `/apps/${app.id}`,
    })
  }

  for (const exec of exs) {
    results.push({
      id: exec.id,
      category: 'exchange',
      title: `${exec.orderId} — ${exec.route}`,
      badges: [{ label: statusLabel(exec.status), color: statusToVariant(exec.status) }],
      meta: `${exec.correlationId} · ${formatDuration(exec.durationMs)} · ${exec.customer}`,
      timestamp: formatTimestamp(exec.timestamp),
      path: `/exchanges/${exec.id}`,
    })
  }

  const routeToApp = buildRouteToAppMap(apps)
  for (const route of rts) {
    const appIdForRoute = routeToApp.get(route.id)
    results.push({
      id: route.id,
      category: 'route',
      title: route.name,
      badges: [{ label: route.group }],
      meta: `${route.exchangeCount.toLocaleString()} exchanges · ${route.successRate}% success`,
      path: appIdForRoute ? `/apps/${appIdForRoute}/${route.id}` : `/apps/${route.id}`,
    })
  }

  for (const agent of ags) {
    results.push({
      id: agent.id,
      category: 'agent',
      title: agent.name,
      badges: [{ label: agent.status }],
      meta: `${agent.service} ${agent.version} · ${agent.tps} · ${agent.lastSeen}`,
      path: `/agents/${agent.appId}/${agent.id}`,
    })
  }

  return results
}
