const express = require("express");
const cors = require("cors");
const path = require("path");
const User = require("./models/user.model");
const requestIdMiddleware = require("./middleware/request-id");
const { sendError } = require("./utils/http");

const app = express();
app.use(requestIdMiddleware);
app.use(express.json());

// Expose manual API test pages in non-production environments only.
if (process.env.NODE_ENV !== "production") {
  app.use("/test", express.static(path.join(__dirname, "public")));
}

const allowedOrigins = (process.env.ALLOWED_ORIGINS || "")
  .split(",")
  .map((origin) => origin.trim())
  .filter(Boolean);
app.use(
  cors({
    origin: function (origin, callback) {
      if (!origin) return callback(null, true);
      if (allowedOrigins.includes(origin)) return callback(null, true);
      if (/^http:\/\/192\.168\.\d+\.\d+/.test(origin)) return callback(null, true);
      if (/^https:\/\/192\.168\.\d+\.\d+/.test(origin)) return callback(null, true);
      console.error(`CORS blocked origin: ${origin}`);
      callback(new Error(`CORS blocked: ${origin}. Add this origin to ALLOWED_ORIGINS environment variable.`));
    },
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
    credentials: true,
    exposedHeaders: ["X-Request-Id"],
  })
);

app.get('/', async (req, res) => {
  res.status(200).json({
    message: "Grocery List API is running.",
    roles: Object.values(User.ROLES),
  });
});


const authRoutes = require("./routes/auth.routes");
app.use("/auth", authRoutes);

const listRoutes = require("./routes/list.routes");
app.use("/list", listRoutes);

const adminRoutes = require("./routes/admin.routes");
app.use("/admin", adminRoutes);

const usersRoutes = require("./routes/users.routes");
app.use("/users", usersRoutes);

const configRoutes = require("./routes/config.routes");
app.use("/config", configRoutes);

const householdsRoutes = require("./routes/households.routes");
app.use("/households", householdsRoutes);

const storesRoutes = require("./routes/stores.routes");
app.use("/stores", storesRoutes);

const groupInvitesRoutes = require("./routes/group-invites.routes");
app.use("/api", groupInvitesRoutes);

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

  const statusCode = err.status || err.statusCode || 500;
  const message =
    statusCode >= 500 ? "Internal server error" : err.message || "Request failed";

  return sendError(res, statusCode, message);
});

module.exports = app;
