const crypto = require('crypto');

/**
 * Authenticate requests from GameForge API
 * Verifies API key and signature to ensure requests are authentic
 */
module.exports = async function gameforgeAuth(req, res, next) {
  try {
    const apiKey = req.headers['x-gameforge-api-key'];
    const signature = req.headers['x-gameforge-signature'];
    const timestamp = req.headers['x-gameforge-timestamp'];

    if (!apiKey || !signature || !timestamp) {
      return res.status(401).json({
        success: false,
        error: 'Missing authentication headers'
      });
    }

    // Verify API key
    if (apiKey !== process.env.GAMEFORGE_API_KEY) {
      return res.status(401).json({
        success: false,
        error: 'Invalid API key'
      });
    }

    // Verify timestamp (prevent replay attacks)
    const requestTime = parseInt(timestamp);
    const currentTime = Date.now();
    const timeDiff = Math.abs(currentTime - requestTime);

    if (timeDiff > 300000) { // 5 minutes
      return res.status(401).json({
        success: false,
        error: 'Request timestamp expired'
      });
    }

    // Verify signature
    const payload = JSON.stringify(req.body);
    const expectedSignature = crypto
      .createHmac('sha256', process.env.GAMEFORGE_API_SECRET)
      .update(`${timestamp}.${payload}`)
      .digest('hex');

    if (signature !== expectedSignature) {
      return res.status(401).json({
        success: false,
        error: 'Invalid signature'
      });
    }

    next();

  } catch (error) {
    console.error('GameForge auth error:', error);
    res.status(500).json({
      success: false,
      error: 'Authentication failed'
    });
  }
};
