import { createHmac, timingSafeEqual } from 'node:crypto';

const MAX_BODY_BYTES = 65_536;
const TIMESTAMP_TOLERANCE_SECONDS = 300;

/** @param {string} secret */
const signingKey = (secret) => {
	if (!/^whsec_[A-Za-z0-9_-]{43}$/.test(secret)) return null;
	const encoded = secret.slice('whsec_'.length);
	const key = Buffer.from(encoded, 'base64url');
	return key.byteLength === 32 && key.toString('base64url') === encoded ? key : null;
};

/**
 * @param {{
 *   headers: Record<string, string | undefined>;
 *   rawBody: Uint8Array;
 *   secret: string;
 *   nowSeconds?: number;
 * }} input
 */
export const verifyHokoWebhook = ({ headers, rawBody, secret, nowSeconds = Date.now() / 1000 }) => {
	const body = Buffer.from(rawBody);
	const id = headers['webhook-id'];
	const timestamp = headers['webhook-timestamp'];
	const signature = headers['webhook-signature'];
	const key = signingKey(secret);
	if (
		!id ||
		!/^\d+$/.test(timestamp ?? '') ||
		!signature?.startsWith('v1,') ||
		body.byteLength > MAX_BODY_BYTES ||
		!key
	)
		return false;
	const issuedAt = Number(timestamp);
	if (
		!Number.isSafeInteger(issuedAt) ||
		Math.abs(nowSeconds - issuedAt) > TIMESTAMP_TOLERANCE_SECONDS
	)
		return false;
	const encodedSignature = signature.slice(3);
	const received = Buffer.from(encodedSignature, 'base64');
	const expected = createHmac('sha256', key)
		.update(Buffer.concat([Buffer.from(`${id}.${timestamp}.`), body]))
		.digest();
	if (
		received.byteLength !== expected.byteLength ||
		received.toString('base64') !== encodedSignature ||
		!timingSafeEqual(received, expected)
	)
		return false;
	try {
		const event = JSON.parse(body.toString('utf8'));
		return event && !Array.isArray(event) && typeof event === 'object' && event.id === id;
	} catch {
		return false;
	}
};

/**
 * `storeOnce` must atomically insert a durable unique receipt for `event.id` and persist or
 * enqueue the event. Return false when that receipt already exists. Never use an in-memory Set
 * in production.
 *
 * @param {{
 *   secret?: string;
 *   nowSeconds?: () => number;
 *   storeOnce: (event: Record<string, any>) => Promise<boolean>;
 * }} dependencies
 */
export const createHokoWebhookHandler =
	({
		secret = process.env.HOKO_WEBHOOK_SECRET ?? '',
		nowSeconds = () => Date.now() / 1000,
		storeOnce
	}) =>
	/** @param {{ headers: Record<string, string | undefined>; rawBody: Uint8Array }} request */
	async ({ headers, rawBody }) => {
		if (!verifyHokoWebhook({ headers, rawBody, secret, nowSeconds: nowSeconds() })) {
			return { status: 400 };
		}
		const event = JSON.parse(Buffer.from(rawBody).toString('utf8'));
		if (event.type === 'endpoint.verification') {
			if (typeof event.data?.challenge !== 'string') return { status: 400 };
			return {
				status: 200,
				headers: { 'content-type': 'application/json' },
				body: JSON.stringify({ challenge: event.data.challenge })
			};
		}
		return (await storeOnce(event)) ? { status: 202 } : { status: 204 };
	};
