import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createNotification, getNotifications } from "./db.js";

const PORT = parseInt(process.env.NOTIFICATIONS_SERVICE_PORT || "8087", 10);

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

function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
  return new Promise((resolve) => {
    let data = "";
    req.on("data", (chunk: Buffer) => { data += chunk; });
    req.on("end", () => {
      try {
        resolve(JSON.parse(data || "{}") as Record<string, unknown>);
      } catch {
        resolve({});
      }
    });
  });
}

const server = createServer(async (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");

  if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; }

  const path = (req.url || "/").split("?")[0];

  if (req.method === "GET" && path === "/health") {
    json(res, { ok: true });
    return;
  }

  if (req.method === "GET" && path === "/notifications") {
    try {
      json(res, getNotifications());
    } catch (e) {
      json(res, { error: e instanceof Error ? e.message : "Unknown error" }, 500);
    }
    return;
  }

  if (req.method === "POST" && path === "/notifications") {
    try {
      const body = await readBody(req);
      const title = typeof body.title === "string" ? body.title : null;
      if (!title) { json(res, { error: "title is required" }, 400); return; }
      const description = typeof body.description === "string" ? body.description : undefined;
      const source = typeof body.source === "string" ? body.source : undefined;
      const level = typeof body.level === "string" ? body.level : undefined;
      const notification = createNotification({ title, description, source, level });
      json(res, notification, 201);
    } catch (e) {
      json(res, { error: e instanceof Error ? e.message : "Unknown error" }, 500);
    }
    return;
  }

  json(res, { error: "Not found" }, 404);
});

server.listen(PORT, () => {
  console.log(`Notifications service listening on port ${PORT}`);
});
