import { toSnapshotRead } from "../../../services/poller.js"
import {
  createServerRow,
  deleteServerRowById,
  getLatestSnapshot,
  getServerRowById,
  listServerRows,
  listSnapshotsByServerId,
  updateServerRowById,
} from "../repository/servers-repository.js"
import { toServerRead } from "../mapper/servers-mapper.js"
import type { ServerCreate, ServerRead, ServerUpdate, SnapshotRead } from "../../../types/server.js"

export function listServersRead(): ServerRead[] {
  return listServerRows().map((server) => toServerRead(server, getLatestSnapshot(server.id)))
}

export function getServerReadById(id: number): ServerRead | undefined {
  const row = getServerRowById(id)
  if (!row) return undefined
  return toServerRead(row, getLatestSnapshot(row.id))
}

export function createServer(input: ServerCreate): ServerRead {
  const now = new Date().toISOString()
  const { wanUplinks, ...rest } = input
  const inserted = createServerRow({
    ...rest,
    wanUplinks: JSON.stringify(wanUplinks ?? []),
    createdAt: now,
    updatedAt: now,
  })
  return toServerRead(inserted, undefined)
}

export function updateServer(id: number, input: ServerUpdate): ServerRead {
  const { wanUplinks, ...rest } = input
  const setPayload: Record<string, unknown> = { updatedAt: new Date().toISOString() }
  for (const [k, v] of Object.entries(rest)) {
    if (v !== undefined) setPayload[k] = v
  }
  if (wanUplinks !== undefined) {
    setPayload.wanUplinks = JSON.stringify(wanUplinks)
  }
  const updated = updateServerRowById(id, setPayload as never)
  return toServerRead(updated, getLatestSnapshot(updated.id))
}

export function deleteServer(id: number): void {
  deleteServerRowById(id)
}

export function listServerSnapshots(id: number, limit: number): SnapshotRead[] {
  return listSnapshotsByServerId(id, limit).map(toSnapshotRead)
}
