// src/middleware/verifyWebhook.js
// HMAC SHA256 webhook signature verification for Paymenter webhooks

const crypto = require('crypto');

/**
 * Verify webhook signature to prevent unauthorized requests
 * @param {Object} req - Express request
 * @param {Object} res - Express response
 * @param {Function} next - Express next function
 */
function verifyBillingWebhook(req, res, next) {
    const signature = req.headers['x-signature']; // Check your provider's exact header name
    const payload = JSON.stringify(req.body);
    const secret = process.env.WEBHOOK_SECRET;

    if (!signature || !secret) {
        console.error('[Webhook] Missing signature or secret');
        return res.status(401).json({ error: 'Invalid webhook signature' });
    }

    const expectedSignature = crypto
        .createHmac('sha256', secret)
        .update(payload)
        .digest('hex');

    if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
        console.error('[Webhook] Signature verification failed');
        return res.status(401).json({ error: 'Invalid webhook signature' });
    }
    
    next();
}

module.exports = verifyBillingWebhook;
