import type { Server } from "node:http";
import { serve } from "@hono/node-server";
import { createApp } from "./app.js";
import { SignalingServer } from "./ws/signaling.js";

/**
 * Hono API + WebSocket signalling — GDD §4, §8, §9.
 *
 * Storage is in-memory until Neon credentials exist; `db/schema.sql` is already
 * the target shape and `Store` is the seam.
 */
const { app, store } = createApp();
const port = Number(process.env["PORT"] ?? 8787);

const server = serve({ fetch: app.fetch, port }, (info) => {
  console.log(`psx server listening on http://localhost:${info.port}`);
  console.log(`signalling on ws://localhost:${info.port}/ws`);
});

// `serve` returns the underlying Node http server, which `ws` attaches to.
const signaling = new SignalingServer(server as unknown as Server, store);

for (const signal of ["SIGINT", "SIGTERM"] as const) {
  process.on(signal, () => {
    signaling.close();
    server.close(() => process.exit(0));
  });
}

export { app, store };
