import express from "express";
import cookieParser from "cookie-parser";
import Pino from "express-pino-logger";
import cors from "cors";
import routerStations from "./routes/v1/stations";
import config from "./config";
import { formatResponseError } from "./libs/Format";

// Initialisation du logger
const pino = new Pino({
  prettyPrint: true
});
pino.logger.info(`Server started on port ${config.port}`);

const app = express();

app.use(cors());

// Permet de sauvegarder l'ip du client et non du proxy
app.set("trust proxy", config.trustProxy);
app.use(cookieParser());
// Utilisation de Pino
app.use(pino);

// Déclaration des routes
app.use("/v1/stations", routerStations);

// Gestion des erreurs
app.use((err, req, res, next) => {
  res.error = err;
  if (res.headersSent) {
    next(err);
  } else {
    formatResponseError(res, err);
  }
});

module.exports = app;
