//import { initPackages } from "@/core/package-loader";
import dotenv from "dotenv";
import express, { Application } from "express";
import helmet from "helmet";
import responseTime from "response-time";
import { globalErrorHandler } from "./core/common/presentation";
import { logger } from "./core/logger";

dotenv.config();

export function createApp(): Application {
  const app = express();
  app.set("port", process.env.PORT ?? 3002);

  // secure apps by setting various HTTP headers
  app.disable("x-powered-by");

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

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

  // 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");
    res.setHeader("etag", "false");
    next(); // Continúa con la siguiente función middleware o la ruta
  });

  // Inicializar Auth Provider
  app.use((req, res, next) => {
    //authProvider.initialize();
    next();
  });

  app.use((req, _, next) => {
    logger.info(`▶️  Incoming request ${req.method} to ${req.path}`);
    next();
  });

  // Registrar rutas de la API
  //  app.use("/api/v1", v1Routes());
  //initModules(app, database);

  // Gestión global de errores.
  // Siempre al final de la cadena de middlewares
  // y después de las rutas.
  app.use(globalErrorHandler);

  return app;
}
