import type { IncomingMessage, ServerResponse } from "node:http";
import {
  getSnapshot,
  getHosts,
  getHost,
  getServices,
  getService,
  getNetworkStatuses,
  getSites,
  getSite,
  getAlerts,
  getSummary,
} from "./cache.js";

function json(res: ServerResponse, data: unknown, status = 200): void {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
}

function error(res: ServerResponse, message: string, status = 400): void {
  json(res, { error: message }, status);
}

const startedAt = Date.now();

export function handleHealth(_req: IncomingMessage, res: ServerResponse): void {
  json(res, { status: "online", uptime: Math.floor((Date.now() - startedAt) / 1000), version: "1.0.0" });
}

export function handleGetStatus(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getSnapshot());
}

export function handleGetHosts(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getHosts());
}

export function handleGetHost(_req: IncomingMessage, res: ServerResponse, id: string): void {
  const host = getHost(id);
  if (!host) return error(res, "Host not found", 404);
  json(res, host);
}

export function handleGetServices(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getServices());
}

export function handleGetService(_req: IncomingMessage, res: ServerResponse, id: string): void {
  const svc = getService(id);
  if (!svc) return error(res, "Service not found", 404);
  json(res, svc);
}

export function handleGetNetwork(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getNetworkStatuses());
}

export function handleGetSites(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getSites());
}

export function handleGetSite(_req: IncomingMessage, res: ServerResponse, id: string): void {
  const site = getSite(id);
  if (!site) return error(res, "Site not found", 404);
  json(res, site);
}

export function handleGetAlerts(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getAlerts());
}

export function handleGetSummary(_req: IncomingMessage, res: ServerResponse): void {
  json(res, getSummary());
}
