const { allowedOrigins } = require('../config/config');

/**
 * CORS middleware
 * Handles Cross-Origin Resource Sharing for allowed domains
 */
function corsMiddleware(req, res, next) {
  const origin = req.headers.origin;
  
  if (allowedOrigins.indexOf(origin) > -1) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  
  // Handle preflight requests
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }
  
  next();
}

module.exports = corsMiddleware;
