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

const healthRouter = require("./routes/health");
const authRouter = require("./routes/auth");
const adminRouter = require("./routes/admin");
const categoriesRouter = require("./routes/categories");
const variationsRouter = require("./routes/variations");
const brandsRouter = require("./routes/brands");
const unitsRouter = require("./routes/units");
const warehousesRouter = require("./routes/warehouses");
const suppliersRouter = require("./routes/suppliers");
const customersRouter = require("./routes/customers");
const paymentMethodsRouter = require("./routes/paymentMethods");
const productsRouter = require("./routes/products");
const taxesRouter = require("./routes/taxes");
const adjustmentsRouter = require("./routes/adjustments");
const invoicesRouter = require("./routes/invoices");
const purchasesRouter = require("./routes/purchases");
const purchaseReturnsRouter = require("./routes/purchaseReturns");
const salesRouter = require("./routes/sales");
const salesReturnsRouter = require("./routes/salesReturns");
const expenseCategoriesRouter = require("./routes/expenseCategories");
const expensesRouter = require("./routes/expenses");
const transfersRouter = require("./routes/transfers");
const rolesRouter = require("./routes/roles");
const permissionsRouter = require("./routes/permissions");
const usersRouter = require("./routes/users");
const uploadsRouter = require("./routes/uploads");
const branchesRouter = require("./routes/branches");
const statsRouter = require("./routes/stats");
const settingsRouter = require("./routes/settings");
const emailTemplatesRouter = require("./routes/emailTemplates");
const smsTemplatesRouter = require("./routes/smsTemplates");
const notificationsRouter = require("./routes/notifications");
const activityLogsRouter = require("./routes/activityLogs");
const prisma = require("./prisma");

const app = express();

app.use(createCorsMiddleware());
app.use(express.json({ limit: "2mb" }));
app.use(morgan(process.env.NODE_ENV === "production" ? "combined" : "dev"));

app.use("/api/health", healthRouter);
app.use("/api/auth", authRouter);
app.use("/api/admin", adminRouter);
app.use("/api/categories", categoriesRouter);
app.use("/api/variations", variationsRouter);
app.use("/api/brands", brandsRouter);
app.use("/api/units", unitsRouter);
app.use("/api/warehouses", warehousesRouter);
app.use("/api/suppliers", suppliersRouter);
app.use("/api/customers", customersRouter);
app.use("/api/payment-methods", paymentMethodsRouter);
app.use("/api/products", productsRouter);
app.use("/api/taxes", taxesRouter);
app.use("/api/adjustments", adjustmentsRouter);
app.use("/api/invoices", invoicesRouter);
app.use("/api/purchases", purchasesRouter);
app.use("/api/purchase-returns", purchaseReturnsRouter);
app.use("/api/sales", salesRouter);
app.use("/api/sales-returns", salesReturnsRouter);
app.use("/api/expense-categories", expenseCategoriesRouter);
app.use("/api/expenses", expensesRouter);
app.use("/api/transfers", transfersRouter);
app.use("/api/roles", rolesRouter);
app.use("/api/permissions", permissionsRouter);
app.use("/api/users", usersRouter);
app.use("/api/uploads", uploadsRouter);
app.use("/api/branches", branchesRouter);
app.use("/api/stats", statsRouter);
app.use("/api/settings", settingsRouter);
app.use("/api/email-templates", emailTemplatesRouter);
app.use("/api/sms-templates", smsTemplatesRouter);
app.use("/api/notifications", notificationsRouter);
app.use("/api/activity-logs", activityLogsRouter);

// Express 5 mount matching can be strict; define explicit subpaths.
app.get("/api/health/db", async (req, res) => {
  try {
    await prisma.$queryRawUnsafe("SELECT 1");
    res.json({ ok: true, db: "connected" });
  } catch (err) {
    res.status(500).json({ ok: false, db: "error", error: err.message });
  }
});

app.use((req, res) => {
  res.status(404).json({ error: "Not found" });
});

app.use((err, req, res, _next) => {
  applyCorsHeaders(req, res, collectAllowedOrigins());
  const status = err.status || 500;
  const message =
    process.env.NODE_ENV === "production" && status === 500
      ? "Internal server error"
      : err.message || "Internal server error";
  res.status(status).json({ error: message });
});

module.exports = app;
