import express from "express";
import type { Express } from "express";
import { toNodeHandler } from "better-auth/node";
import cors from "cors";
import helmet from "helmet";
import { auth } from "./lib/auth.js";
import { createApiRouter } from "./routes/apiRouter.js";
import { InMemoryGameSessionStore } from "./gameSessionStore/index.js";
import { errorHandler } from "./middleware/errorHandler.js";
import { authLimiter } from "./middleware/rateLimiters.js";

export function createApp() {
  const app: Express = express();

  app.set("trust proxy", 1);
  app.use(helmet());

  app.use(
    cors({
      origin: process.env["CORS_ORIGIN"] || "http://localhost:5173",
      credentials: true,
    }),
  );
  app.use("/api/auth", authLimiter);
  app.all("/api/auth/*splat", toNodeHandler(auth));
  app.use(express.json());

  const store = new InMemoryGameSessionStore();
  app.use("/api/v1", createApiRouter(store));

  app.use(errorHandler);

  return app;
}
