import express, { Request, Response, NextFunction } from "express";
import cors from "cors";
import { config } from "./config";
import healthRouter from "./routes/health";
import racesRouter from "./routes/races";

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

  app.use(
    cors({ origin: config.corsOrigin, methods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"] }),
  );
  app.use(express.json());

  app.use("/api", healthRouter);
  app.use("/api", racesRouter);

  app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
    if (err instanceof SyntaxError && "body" in err) {
      res.status(400).json({ error: "validation_error", details: ["Invalid JSON in request body"] });
      return;
    }
    console.error("[app] Unhandled error:", err);
    res.status(500).json({ error: "unknown_error", details: ["Internal server error"] });
  });

  return app;
}
