import cors from "cors";
import express from "express";
import helmet from "helmet";
import responseTime from "response-time";

import { configurePassportAuth } from "@/contexts/auth";
import morgan from "morgan";
import multer from "multer";
import passport from "passport";
import path from "path";
import { config } from "../../config";
import { v1Routes } from "./api/v1";

//const logger = initLogger(rTracer);

// Create Express server
const app = express();

//app.use(rTracer.expressMiddleware());
app.disable("x-powered-by");
app.use(express.json());
app.use(express.text());
app.use(express.urlencoded({ extended: true }));

// set up the response-time middleware
app.use(responseTime());

// enable CORS - Cross Origin Resource Sharing
app.use(
  cors({
    origin: config.server.cors_origin,
    methods: "GET,POST,PUT,DELETE,OPTIONS",
    credentials: true,

    exposedHeaders: [
      "Access-Control-Allow-Headers",
      "Access-Control-Allow-Origin",
      "Content-Disposition",
      "Content-Type",
      "Content-Length",
      "X-Total-Count",
      "Pagination-Count",
      "Pagination-Page",
      "Pagination-Limit",
    ],
  })
);

// secure apps by setting various HTTP headers
app.use(helmet());

// Middleware global para desactivar la caché en todas las rutas
/*app.use((req, res, next) => {
  res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
  res.setHeader("Pragma", "no-cache");
  res.setHeader("Expires", "0");
  next(); // Continúa con la siguiente función middleware o la ruta
  
});
*/

// request logging. dev: console | production: file
//app.use(morgan('common'));
app.use(morgan("dev"));

// Express configuration
app.set("port", process.env.PORT ?? 3001);

// Public assets
app.use("/assets", express.static(path.join(__dirname, "/public")));

// Manejo de errores de multer
app.use((err: any, req: any, res: any, next: any) => {
  if (err instanceof multer.MulterError) {
    // Error de multer
    return res.status(400).json({ error: err.message });
  } else if (err) {
    // Otro tipo de error
    return res.status(500).json({ error: err.message });
  }
  next();
});

// Autentication
app.use(passport.initialize());
configurePassportAuth(passport);

// API
app.use("/api/v1", v1Routes());

export { app };
