import { createHmac } from 'crypto';
import type { IWebhookFunctions } from 'n8n-workflow';

import { verifySignature as verifySignatureGeneric } from '../../../utils/webhook-signature-verification';

/**
 * Verifies the MailerLite webhook signature.
 *
 * MailerLite signs webhooks using HMAC SHA-256:
 * 1. Compute HMAC SHA-256 of the raw JSON payload using the webhook secret
 * 2. Encode as a hex string
 * 3. Compare with the signature in the `Signature` header
 *
 * The secret is generated by MailerLite when the webhook is created and stored
 * in the workflow's static data.
 *
 * @returns true if the signature is valid, false otherwise
 * @returns true if no secret is configured (backward compatibility with old triggers)
 */
export function verifySignature(this: IWebhookFunctions): boolean {
	const req = this.getRequestObject();
	const webhookData = this.getWorkflowStaticData('node');
	const secret = webhookData.webhookSecret;

	return verifySignatureGeneric({
		getExpectedSignature: () => {
			if (!secret || typeof secret !== 'string' || !req.rawBody) {
				return null;
			}
			const hmac = createHmac('sha256', secret);
			const payload = Buffer.isBuffer(req.rawBody) ? req.rawBody : Buffer.from(req.rawBody);
			hmac.update(payload);
			return hmac.digest('hex');
		},
		skipIfNoExpectedSignature: !secret || typeof secret !== 'string',
		getActualSignature: () => {
			const receivedSignature = req.header('signature');
			return typeof receivedSignature === 'string' ? receivedSignature : null;
		},
	});
}
