const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const config = require('../config/env.js');

/**
 * Configure CORS middleware
 */
const corsOptions = {
  origin: config.nodeEnv === 'production' ? process.env.ALLOWED_ORIGINS?.split(',') : '*',
  credentials: true,
  optionsSuccessStatus: 200,
};

/**
 * Configure rate limiting middleware
 */
const limiter = rateLimit({
  windowMs: config.rateLimit.windowMs,
  max: config.rateLimit.max,
  message: 'Too many requests from this IP, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
});

/**
 * Apply security middleware to Express app
 */
const applySecurityMiddleware = (app) => {
  // Helmet for security headers with relaxed CSP for development
  app.use(
    helmet({
      contentSecurityPolicy: {
        directives: {
          ...helmet.contentSecurityPolicy.getDefaultDirectives(),
          'img-src': ["'self'", 'data:', '*'], // Allow images from any source
        },
      },
      crossOriginResourcePolicy: { policy: 'cross-origin' }, // Allow cross-origin resource loading
    })
  );

  // CORS
  app.use(cors(corsOptions));

  // Rate limiting
  app.use('/api/', limiter);
};

module.exports = {
  applySecurityMiddleware,
  corsOptions,
  limiter,
};
