import type { ServerRead, WanUplinkRead } from "../../../types/server.js"
import type { ServerRow, SnapshotRow } from "../repository/servers-repository.js"

function parseWanUplinksJson(raw: string | null | undefined): WanUplinkRead[] {
  if (raw == null || raw === "") return []
  try {
    const data = JSON.parse(raw) as unknown
    if (!Array.isArray(data)) return []
    const out: WanUplinkRead[] = []
    for (const row of data) {
      if (typeof row !== "object" || row === null) continue
      const r = row as Record<string, unknown>
      out.push({
        id: typeof r.id === "string" ? r.id : "",
        name: typeof r.name === "string" ? r.name : "",
        isp: typeof r.isp === "string" ? r.isp : "",
        iface: typeof r.iface === "string" ? r.iface : "",
        ip: typeof r.ip === "string" ? r.ip : "",
        maxDl: typeof r.maxDl === "number" && Number.isFinite(r.maxDl) ? r.maxDl : 0,
        maxUl: typeof r.maxUl === "number" && Number.isFinite(r.maxUl) ? r.maxUl : 0,
      })
    }
    return out
  } catch {
    return []
  }
}

export function toServerRead(server: ServerRow, snap: SnapshotRow | undefined): ServerRead {
  return {
    id: server.id,
    name: server.name || server.host,
    host: server.host,
    port: server.port,
    useSsl: server.useSsl,
    verifySsl: server.verifySsl,
    username: server.username,
    password: server.password,
    type: server.type,
    site: server.site,
    country: server.country,
    asn: server.asn,
    comment: server.comment,
    enabled: server.enabled,
    lanSubnet: server.lanSubnet ?? "",
    wanUplinks: parseWanUplinksJson(server.wanUplinks),
    createdAt: server.createdAt,
    updatedAt: server.updatedAt,
    status: snap ? snap.status : null,
    latency: snap?.latencyMs ?? null,
    os: snap?.rosVersion ?? null,
    model: snap?.boardName ?? null,
    uptime: snap?.uptime ?? null,
    cpuLoad: snap?.cpuLoad ?? null,
    freeMemory: snap?.freeMemory ?? null,
    totalMemory: snap?.totalMemory ?? null,
    identityName: snap?.identityName ?? null,
    sessions: 0,
    polledAt: snap?.polledAt ?? null,
  }
}
