import { Hono } from "hono";
import { cors } from "hono/cors";
import { InMemoryStore, type Store } from "./db/store.js";
import { authRoutes } from "./routes/auth.js";
import { lobbyRoutes } from "./routes/lobbies.js";
import { savesRoutes } from "./routes/saves.js";

/**
 * Route wiring, separated from the bootstrap so tests can mount the app
 * against a fresh store without opening a port.
 */
export function createApp(store: Store = new InMemoryStore()) {
  const app = new Hono();

  // The client page is cross-origin isolated (for wasm threads), which does not
  // restrict its own outbound fetches, but in dev it runs on a different port.
  app.use("/*", cors({ origin: (origin) => origin ?? "*", credentials: true }));

  app.get("/health", (context) =>
    context.json({ ok: true, storage: "in-memory", version: "0.1.0" }),
  );

  app.route("/auth", authRoutes(store));
  app.route("/lobbies", lobbyRoutes(store));
  app.route("/saves", savesRoutes(store));

  return { app, store };
}
