import { getLogger } from "../logger.js";
import { FileSecurityError } from "../domains/run/services/blob-storage/file-security-errors.js";
import { WebhookUrlSecurityError, fetchWithSsrfProtection } from "../utils/webhook-url-security.js";
import { WebhookDeliveryPayloadSchema } from "../domains/run/workflow/functions/webhookDelivery.js";
import { handleCallback } from "@vercel/queue";

//#region src/routes/webhookDeliveryConsumer.ts
const logger = getLogger("webhook-delivery-consumer");
var RetryableDeliveryError = class extends Error {};
async function deliverWebhook(payload) {
	const { destinationUrl, webhookDestinationId } = payload;
	try {
		const response = await fetchWithSsrfProtection(destinationUrl, {
			method: "POST",
			headers: {
				...payload.headers,
				"Content-Type": "application/json",
				"User-Agent": "Inkeep-Webhooks/1.0"
			},
			body: JSON.stringify(payload.payload),
			signal: AbortSignal.timeout(3e4)
		});
		if (response.ok) {
			logger.info({
				webhookDestinationId,
				statusCode: response.status
			}, "Webhook delivered successfully");
			return;
		}
		const responseText = await response.text().catch(() => "");
		logger.warn({
			webhookDestinationId,
			statusCode: response.status,
			responseBody: responseText.slice(0, 500)
		}, "Webhook delivery received non-2xx response");
		if (response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429) return;
		throw new RetryableDeliveryError(`Webhook delivery to ${webhookDestinationId} failed with status ${response.status}`);
	} catch (err) {
		if (err instanceof RetryableDeliveryError) throw err;
		if (err instanceof WebhookUrlSecurityError || err instanceof FileSecurityError) {
			logger.warn({
				webhookDestinationId,
				error: err.message
			}, "Webhook delivery blocked by SSRF protection");
			return;
		}
		logger.error({
			webhookDestinationId,
			error: err instanceof Error ? err.message : String(err)
		}, "Webhook delivery failed");
		throw err;
	}
}
async function handleWebhookMessage(message, metadata) {
	const parsed = WebhookDeliveryPayloadSchema.safeParse(message);
	if (!parsed.success) {
		logger.error({
			error: parsed.error.message,
			messageId: metadata.messageId
		}, "Webhook delivery queue message failed schema validation");
		return;
	}
	await deliverWebhook(parsed.data);
}
const POST = handleCallback(handleWebhookMessage);

//#endregion
export { POST, deliverWebhook, handleWebhookMessage };