import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import authRoutes from "./routes/authRoutes.js";
import customersRoutes from "./routes/customersRoutes.js";
import servicesRoutes from "./routes/servicesRoutes.js";
import ordersRoutes from "./routes/ordersRoutes.js";
import paymentMethodsRoutes from "./routes/paymentMethodsRoutes.js";
import settingsRoutes from "./routes/settingsRoutes.js";
import usersRoutes from "./routes/usersRoutes.js";
import loyaltyRoutes from "./routes/loyaltyRoutes.js";
import reportsRoutes from "./routes/reportsRoutes.js";
import inventoryRoutes from "./routes/inventoryRoutes.js";
import suppliersRoutes from "./routes/suppliersRoutes.js";
import backupRoutes from "./routes/backupRoutes.js";
import auditRoutes from "./routes/auditRoutes.js";
import cashRegisterRoutes from "./routes/cashRegisterRoutes.js";
import { requireAuth } from "./middleware/auth.js";
import { auditMutationLogger } from "./middleware/auditLogger.js";
import { errorHandler } from "./middleware/errorHandler.js";

dotenv.config();

const app = express();
const PORT = process.env.PORT || 4000;

app.use(cors({
  origin: process.env.FRONTEND_URL || "http://localhost:5173"
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get(["/health", "/api/health", "/node-api/api/health"], (req, res) => {
  res.json({
    success: true,
    message: "Laundry App API running"
  });
});

const apiPrefixes = ["", "/api", "/node-api/api"];

for (const prefix of apiPrefixes) {
  app.use(`${prefix}/auth`, authRoutes);
  app.use(`${prefix}/customers`, requireAuth, auditMutationLogger, customersRoutes);
  app.use(`${prefix}/services`, requireAuth, auditMutationLogger, servicesRoutes);
  app.use(`${prefix}/orders`, requireAuth, auditMutationLogger, ordersRoutes);
  app.use(`${prefix}/payment-methods`, requireAuth, auditMutationLogger, paymentMethodsRoutes);
  app.use(`${prefix}/settings`, requireAuth, auditMutationLogger, settingsRoutes);
  app.use(`${prefix}/users`, usersRoutes);
  app.use(`${prefix}/loyalty`, requireAuth, auditMutationLogger, loyaltyRoutes);
  app.use(`${prefix}/reports`, requireAuth, reportsRoutes);
  app.use(`${prefix}/inventory`, requireAuth, auditMutationLogger, inventoryRoutes);
  app.use(`${prefix}/suppliers`, requireAuth, auditMutationLogger, suppliersRoutes);
  app.use(`${prefix}/cash-register`, requireAuth, auditMutationLogger, cashRegisterRoutes);
  app.use(`${prefix}/backup`, requireAuth, backupRoutes);
  app.use(`${prefix}/audit`, requireAuth, auditRoutes);
}

app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: "Ruta no encontrada"
  });
});

app.use(errorHandler);

app.listen(PORT, () => {
  console.log(`Laundry App API running on http://localhost:${PORT}`);
});
