import { deliverWebhookStep, logStep } from "../steps/webhookDeliverySteps.js";
import { getWorkflowMetadata, sleep } from "workflow";
import { z } from "zod";

//#region src/domains/run/workflow/functions/webhookDelivery.ts
const WebhookDeliveryPayloadSchema = z.object({
	destinationUrl: z.string().min(1),
	tenantId: z.string().min(1),
	projectId: z.string().min(1),
	agentId: z.string(),
	webhookDestinationId: z.string().min(1),
	payload: z.record(z.string(), z.unknown()),
	headers: z.record(z.string(), z.string()).nullish()
});
const MAX_ATTEMPTS = 3;
const BASE_RETRY_DELAY_MS = 2e3;
async function _webhookDeliveryWorkflow(deliveryPayload) {
	"use workflow";
	const { destinationUrl, tenantId, projectId, agentId, webhookDestinationId, payload, headers } = deliveryPayload;
	const metadata = getWorkflowMetadata();
	await logStep("Starting webhook delivery workflow", {
		tenantId,
		projectId,
		agentId,
		webhookDestinationId,
		destinationUrl,
		eventType: payload.type,
		workflowRunId: metadata.workflowRunId
	});
	let lastError;
	for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
		const result = await deliverWebhookStep({
			destinationUrl,
			payload,
			headers
		});
		if (result.success) {
			await logStep("Webhook delivered successfully", {
				webhookDestinationId,
				attempt,
				statusCode: result.statusCode
			});
			return {
				status: "delivered",
				attempt,
				statusCode: result.statusCode
			};
		}
		lastError = result.error;
		if (result.statusCode && result.statusCode >= 400 && result.statusCode < 500 && result.statusCode !== 408 && result.statusCode !== 429 || result.blocked) {
			await logStep("Webhook delivery failed with non-retryable status", {
				webhookDestinationId,
				attempt,
				statusCode: result.statusCode,
				error: lastError
			});
			return {
				status: "failed",
				attempt,
				statusCode: result.statusCode,
				error: lastError
			};
		}
		if (attempt < MAX_ATTEMPTS) await sleep(BASE_RETRY_DELAY_MS * 2 ** (attempt - 1) * (1 + Math.random() * .3));
	}
	await logStep("Webhook delivery exhausted all retries", {
		webhookDestinationId,
		maxAttempts: MAX_ATTEMPTS,
		error: lastError
	});
	return {
		status: "failed",
		attempt: MAX_ATTEMPTS,
		error: lastError
	};
}
const webhookDeliveryWorkflow = Object.assign(_webhookDeliveryWorkflow, { workflowId: "workflow//./src/domains/run/workflow/functions/webhookDelivery//_webhookDeliveryWorkflow" });

//#endregion
export { WebhookDeliveryPayloadSchema, webhookDeliveryWorkflow };