const express = require('express');
const helmet = require('helmet');
const morgan = require('morgan');
const cors = require('cors');
const i18n = require('i18n');
const path = require('path');
const { rateLimit } = require('../middleware/rateLimit');
const { errorHandler } = require('../middleware/error');
const { notFound } = require('../middleware/error');

function setupExpress(app, corsOptions) {
  // sicurezza base
  app.use(helmet());
  app.use(morgan('dev'));
  app.use(cors(corsOptions));
  app.set('trust proxy', true);

  // parser
  app.use(express.json({ limit: '100mb' }));
  app.use(express.urlencoded({ extended: true, limit: '100mb' }));

  // i18n
  i18n.configure({
    locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
    defaultLocale: 'it',
    directory: path.join(__dirname, '../locales'),
    api: { __: 'translate', __n: 'translateN' },
  });
  app.use(i18n.init);

  // sicurezza aggiuntiva
  app.use(rateLimit);
  app.use(express.static('views'));

  // health check
  app.get('/health', (_req, res) => res.json({ ok: true }));

  // error handler
  app.use(errorHandler);

  // app.use(notFound); // gestione 404

  return app;
}

module.exports = { setupExpress };
