require("dotenv").config();

const express = require("express");
const { applyCorsHeaders, collectAllowedOrigins } = require("../src/lib/cors");

let app;

try {
  app = require("../src/app");
} catch (err) {
  console.error("Failed to boot API:", err);
  app = express();
  app.use((req, res) => {
    applyCorsHeaders(req, res, collectAllowedOrigins());
    if (req.method === "OPTIONS") return res.status(204).end();
    res.status(500).json({
      error: "API failed to start",
      detail: process.env.NODE_ENV === "production" ? undefined : err.message,
    });
  });
}

module.exports = app;
