/** Narrow unknown JSON / fetch payloads for strict TypeScript. */

export interface PrometheusQueryResponse {
  status: string
  data?: {
    result?: Array<{
      values?: Array<[number | string, string]>
    }>
  }
}

export interface ProxmoxListResponse<T = unknown> {
  data: T
}

export function asRecord(value: unknown): Record<string, unknown> {
  return (typeof value === 'object' && value !== null ? value : {}) as Record<string, unknown>
}

export function asString(value: unknown, fallback = ''): string {
  if (typeof value === 'string') return value
  if (typeof value === 'number' || typeof value === 'boolean') return String(value)
  return fallback
}

export function asNumber(value: unknown, fallback = 0): number {
  if (typeof value === 'number' && !Number.isNaN(value)) return value
  if (typeof value === 'string') {
    const parsed = Number(value)
    return Number.isNaN(parsed) ? fallback : parsed
  }
  return fallback
}

export function asArray<T = unknown>(value: unknown): T[] {
  return Array.isArray(value) ? (value as T[]) : []
}

export function asDate(value: unknown): Date {
  if (value instanceof Date) return value
  if (typeof value === 'string' || typeof value === 'number') return new Date(value)
  return new Date()
}

export function asPrometheusResponse(value: unknown): PrometheusQueryResponse {
  return asRecord(value) as unknown as PrometheusQueryResponse
}

export function asProxmoxResponse<T>(value: unknown): ProxmoxListResponse<T> {
  return asRecord(value) as unknown as ProxmoxListResponse<T>
}
