import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import { IS_PRODUCTION, SITE_HOST, SITE_URL } from "./config.js";
import { registerApiRoutes } from "./routes/api.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const distPath = path.resolve(__dirname, "../../fe/dist");

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

  app.set("trust proxy", true);
  app.use(express.json());

  app.use((req, res, next) => {
    if (!IS_PRODUCTION) {
      return next();
    }

    const host = req.get("host");

    if (!host || host === SITE_HOST) {
      return next();
    }

    const redirectTarget = new URL(req.originalUrl, SITE_URL);
    res.redirect(301, redirectTarget.toString());
  });

  app.use(express.static(distPath));

  registerApiRoutes(app);

  app.use("/api", (req, res) => {
    res.status(404).json({
      error: "API route not found.",
      path: req.originalUrl,
    });
  });

  app.get("*", (req, res, next) => {
    const indexFile = path.join(distPath, "index.html");

    res.sendFile(indexFile, (error) => {
      if (error) {
        if (req.path.startsWith("/api/")) {
          return next();
        }

        res.status(503).json({
          error: "Frontend build not found. Run `npm --prefix fe run build` first.",
        });
      }
    });
  });

  app.use((err, req, res, next) => {
    res.status(500).json({
      error: "Internal server error.",
      details: err.message,
    });
  });

  return app;
}
