import "dotenv/config";
import express, { type Express, type Router } from "express";
import { createServer, type Server } from "http";
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { registerUploadRoutes } from "./uploads";
import { registerDebugLogRoutes } from "./debuglog";
import { registerSessionStreamRoutes } from "../session-stream";
import { appRouter } from "../routers";
import { createContext } from "./context";

export type CreatedApp = {
  app: Express;
  server: Server;
  coreRouter: Router;
};

/**
 * Builds the Express app + HTTP server + "core" router shared by both the
 * production entry point (`index.ts`) and the development entry point
 * (`dev.ts`). Keeping this in its own module means `index.ts` — the file
 * esbuild bundles into `dist/index.js` — never has to import anything
 * related to Vite.
 */
export function createApp(): CreatedApp {
  const app = express();

  // cPanel/CloudLinux serves this app behind an Apache/LiteSpeed (Passenger)
  // reverse proxy. Trusting it lets Express read X-Forwarded-* headers so
  // req.protocol/req.secure are correct (needed for secure cookies on HTTPS).
  app.set("trust proxy", 1);

  const server = createServer(app);

  app.use(express.json({ limit: "50mb" }));
  app.use(express.urlencoded({ limit: "50mb", extended: true }));

  // All API routes live on a router so they can be mounted both at "/" and
  // under a sub-path (e.g. "/app") — see BASE_PATH in .env. This covers
  // cPanel setups where "Application URL" points at a sub-folder.
  const coreRouter = express.Router();

  registerUploadRoutes(coreRouter);
  registerDebugLogRoutes(coreRouter);
  registerSessionStreamRoutes(coreRouter);

  coreRouter.use(
    "/api/trpc",
    createExpressMiddleware({
      router: appRouter,
      createContext,
    })
  );

  return { app, server, coreRouter };
}
