const cors = require('cors');

// Single CORS middleware for all endpoints
const corsMiddleware = cors({
  origin: [
    'https://inventory.kent.pw',
    'http://localhost:5175',
    'https://acot.site',
    'https://tools.acherryontop.com',
    /^http:\/\/192\.168\.\d+\.\d+(:\d+)?$/,
    /^http:\/\/10\.\d+\.\d+\.\d+(:\d+)?$/
  ],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['Content-Type'],
  credentials: true
});

// Error handler for CORS
const corsErrorHandler = (err, req, res, next) => {
  if (err.message === 'CORS not allowed') {
    console.error('CORS Error:', {
      origin: req.get('Origin'),
      method: req.method,
      path: req.path,
      headers: req.headers
    });
    res.status(403).json({
      error: 'CORS not allowed',
      origin: req.get('Origin'),
      message: 'Origin not in allowed list: https://inventory.kent.pw, https://acot.site, https://tools.acherryontop.com, localhost:5175, 192.168.x.x, or 10.x.x.x'
    });
  } else {
    next(err);
  }
};

module.exports = {
  corsMiddleware,
  corsErrorHandler
}; 