import cors from "@fastify/cors";
import Fastify from "fastify";
import fs from "node:fs/promises";
import path from "node:path";

const app = Fastify({ logger: true });

await app.register(cors, { origin: true });

app.setErrorHandler((err, req, reply) => {
  req.log.error({ err }, "Unhandled error");
  if (reply.sent) return;

  const statusCode =
    typeof (err as { statusCode?: unknown }).statusCode === "number" ? (err as { statusCode: number }).statusCode : 500;
  reply.code(statusCode).send({
    success: false,
    message: err instanceof Error ? err.message : String(err),
    data: [],
    errorCode: "INTERNAL",
  });
});

app.get("/health", async () => ({ ok: true }));

app.get("/zones", async (_req, reply) => {
  const zonesPath = path.resolve(
    process.cwd(),
    "..",
    "web",
    "public",
    "data",
    "zones",
    "zones.wgs84.geojson",
  );
  const txt = await fs.readFile(zonesPath, "utf-8");
  reply.type("application/json").send(JSON.parse(txt));
});

app.get("/vessels", async () => {
  return {
    source: "todo",
    vessels: [],
  };
});

const port = Number(process.env.PORT || 5174);
const host = process.env.HOST || "127.0.0.1";

await app.listen({ port, host });
