import type { AdapterStatus, Panel, StateResponse } from './collector-types'

function isRecord(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
}

function isPanel(value: unknown): value is Panel {
  return isRecord(value)
    && typeof value.id === 'string'
    && typeof value.ts === 'string'
    && 'data' in value
}

function isAdapterStatus(value: unknown): value is AdapterStatus {
  return isRecord(value)
    && typeof value.id === 'string'
    && typeof value.interval === 'number'
    && typeof value.consecutiveErrors === 'number'
    && typeof value.stale === 'boolean'
}

export function normalizeCollectorStateResponse(payload: unknown): StateResponse {
  if (!isRecord(payload)) return { panels: [], adapters: [] }
  return {
    panels: Array.isArray(payload.panels) ? payload.panels.filter(isPanel) : [],
    adapters: Array.isArray(payload.adapters) ? payload.adapters.filter(isAdapterStatus) : [],
  }
}

export function mergeCollectorPanel(payload: unknown, panel: Panel): StateResponse {
  const state = normalizeCollectorStateResponse(payload)
  return {
    ...state,
    panels: [...state.panels.filter((existing) => existing.id !== panel.id), panel],
  }
}
