import type { GetServerSideProps } from 'next'
import SystemOperationsPage from '@/components/explorer/SystemOperationsPage'
import { fetchPublicJson } from '@/utils/publicExplorer'
import type { CapabilitiesResponse, NetworksConfigResponse, TokenListResponse } from '@/services/api/config'
import type { MissionControlBridgeStatusResponse } from '@/services/api/missionControl'
import type { RouteMatrixResponse } from '@/services/api/routes'
import { normalizeExplorerStats, type ExplorerStats } from '@/services/api/stats'

interface SystemPageProps {
  initialBridgeStatus: MissionControlBridgeStatusResponse | null
  initialNetworksConfig: NetworksConfigResponse | null
  initialTokenList: TokenListResponse | null
  initialCapabilities: CapabilitiesResponse | null
  initialRouteMatrix: RouteMatrixResponse | null
  initialStats: ExplorerStats | null
}

export default function SystemPage(props: SystemPageProps) {
  return <SystemOperationsPage {...props} />
}

export const getServerSideProps: GetServerSideProps<SystemPageProps> = async () => {
  const [bridgeStatus, networksConfig, tokenList, capabilities, routeMatrix, stats] = await Promise.all([
    fetchPublicJson<MissionControlBridgeStatusResponse>('/explorer-api/v1/track1/bridge/status').catch(() => null),
    fetchPublicJson<NetworksConfigResponse>('/api/config/networks').catch(() => null),
    fetchPublicJson<TokenListResponse>('/api/config/token-list').catch(() => null),
    fetchPublicJson<CapabilitiesResponse>('/api/config/capabilities').catch(() => null),
    fetchPublicJson<RouteMatrixResponse>('/token-aggregation/api/v1/routes/matrix?includeNonLive=true').catch(() => null),
    fetchPublicJson('/api/v2/stats').then((value) => normalizeExplorerStats(value as never)).catch(() => null),
  ])

  return {
    props: {
      initialBridgeStatus: bridgeStatus,
      initialNetworksConfig: networksConfig,
      initialTokenList: tokenList,
      initialCapabilities: capabilities,
      initialRouteMatrix: routeMatrix,
      initialStats: stats,
    },
  }
}
