const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const passport = require('passport');
const compression = require('compression');
const { errorHandler } = require('./middleware/errorHandler');
const { logger } = require('./utils/logger');
const { validateRequestSchema } = require('./middleware/validateRequest');
const routes = require('./routes');
require('./config/passport');

const app = express();

app.use(helmet());
app.use(cors());
app.use(compression());
app.use(express.json({ limit: '10kb' }));

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
  message: 'Too many requests from this IP, please try again later.'
});

app.use(limiter);
app.use(passport.initialize());
app.use(validateRequestSchema);

app.use('/api', routes);
app.use(errorHandler);

process.on('unhandledRejection', (err) => {
  logger.error('Unhandled Rejection:', err);
  process.exit(1);
});

module.exports = app;