import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { env } from "./config/env.js";
import { errorHandler } from "./middleware/errorHandler.js";
import { authRouter } from "./modules/auth/routes.js";
import { usersRouter } from "./modules/users/routes.js";
import { syncRouter } from "./modules/sync/routes.js";
import { friendsRouter } from "./modules/friends/routes.js";

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

  app.use(express.json({ limit: "10mb" }));
  app.use(cookieParser());

  // Same-origin in production (served behind nginx). CORS only needed when the
  // frontend dev server runs on a different origin than the API.
  if (env.corsOrigins.length > 0) {
    app.use(cors({ origin: env.corsOrigins, credentials: true }));
  }

  app.get("/api/v1/health", (_req, res) => res.json({ ok: true }));

  app.use("/api/v1/auth", authRouter);
  app.use("/api/v1", usersRouter);
  app.use("/api/v1/sync", syncRouter);
  app.use("/api/v1/friends", friendsRouter);

  app.use(errorHandler);

  return app;
}
