import "./db"; // ensure schema is created before handling requests
import fs from "node:fs";
import path from "node:path";
import cookieParser from "cookie-parser";
import cors from "cors";
import express from "express";
import { env } from "./env";
import { authRouter } from "./routes/auth";
import { attendanceRouter } from "./routes/attendance";
import { adminRouter } from "./routes/admin";
import { shiftsRouter } from "./routes/shifts";
import { closureRouter } from "./routes/closure";

const app = express();

app.use(cors({ origin: env.corsOrigin, credentials: true }));
app.use(express.json());
app.use(cookieParser());

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

app.use("/api/auth", authRouter);
app.use("/api/attendance", attendanceRouter);
app.use("/api/shifts", shiftsRouter);
app.use("/api/closure", closureRouter);
app.use("/api/admin", adminRouter);

// In the production Docker image the built frontend is copied next to this
// bundle as dist/public. Serve it (with an SPA fallback) when present; in dev
// the frontend runs on its own Vite server, so this is simply skipped.
const publicDir = path.join(__dirname, "public");
if (fs.existsSync(publicDir)) {
  app.use(express.static(publicDir));
  app.get(/^(?!\/api\/).*/, (_req, res) => {
    res.sendFile(path.join(publicDir, "index.html"));
  });
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});

app.listen(env.port, () => {
  console.log(`EatMe API listening on http://localhost:${env.port}`);
});
