import "server-only";
import { prisma } from "@formbricks/database";
import {
  type JobExecutionContext,
  type JobHandler,
  type TWebhookDeliveryJobData,
  UnrecoverableError,
} from "@formbricks/jobs";
import { logger } from "@formbricks/logger";
import { InvalidInputError } from "@formbricks/types/errors";
import { isDatabasePoolExhaustionError } from "@/lib/jobs/pool-exhaustion";
import { buildDataByQuestionCode } from "@/lib/response/data-by-question-code";
import { isSurveyOutboundAllowed, surveyOutboundVisibilitySelect } from "@/lib/survey/visibility/outbound";
import { WebhookDnsResolutionError } from "@/lib/utils/validate-webhook-url";
import {
  WebhookDeliveryTimeoutError,
  getWebhookUrlHost,
  sendSignedWebhookRequest,
} from "@/modules/integrations/webhooks/lib/send-signed-webhook";
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
import { type TWebhookDeliveryOutcome, recordWebhookDeliveryOutcome } from "./webhook-delivery-metrics";

/**
 * The wire body. What the pipeline job sent before deliveries were fanned out, plus additive keys only:
 * receivers and their signature checks must not notice the refactor, so the existing keys are pinned by a
 * parity test and a literal key-list test, and a new response column does not slip in unannounced. The
 * additions are `outcome` (ENG-6780), always present and `null` when unset, including for a job queued
 * before the column existed, `dataByQuestionCode` (ENG-6784), absent only for a job queued before
 * `survey.questionCodes` existed, and `calBookingsByQuestionId`, present only when the response holds a
 * Cal.com booking.
 */
export const buildWebhookDeliveryBody = (data: TWebhookDeliveryJobData): string => {
  const resolvedData = resolveStorageUrlsInObject(data.response.data);
  const questionCodes = data.survey.questionCodes;

  return JSON.stringify({
    webhookId: data.webhookId,
    event: data.event,
    data: {
      ...data.response,
      outcome: data.response.outcome ?? null,
      data: resolvedData,
      ...(questionCodes ? { dataByQuestionCode: buildDataByQuestionCode(resolvedData, questionCodes) } : {}),
      // What a Cal.com element reported, beside the unchanged "booked" in `data` (see `extractCalBookings`).
      // Absent unless the response holds a booking, so no other webhook body changes.
      ...(data.calBookings ? { calBookingsByQuestionId: data.calBookings } : {}),
      survey: {
        title: data.survey.name,
        type: data.survey.type,
        status: data.survey.status,
        createdAt: data.survey.createdAt,
        updatedAt: data.survey.updatedAt,
      },
    },
  });
};

/**
 * Receiver answered, but not with a success: worth another attempt only when the condition can change on
 * its own. 5xx, 408 and 429 are the receiver asking us to come back; a 3xx is a redirect we refuse to
 * follow (SSRF policy) and treat as a failure, but the target may fix its config. Every other 4xx means the
 * request itself is rejected — resending identical bytes cannot help.
 */
const isRetryableStatus = (statusCode: number): boolean =>
  statusCode >= 500 || statusCode === 408 || statusCode === 429 || (statusCode >= 300 && statusCode < 400);

const isSuccessStatus = (statusCode: number): boolean => statusCode >= 200 && statusCode < 300;

const getDeliveryLogContext = (data: TWebhookDeliveryJobData, context: JobExecutionContext) => ({
  attempt: context.attempt,
  event: data.event,
  jobId: context.jobId,
  jobName: context.jobName,
  maxAttempts: context.maxAttempts,
  queueName: context.queueName,
  responseId: data.response.id,
  surveyId: data.surveyId,
  webhookId: data.webhookId,
  workspaceId: data.workspaceId,
});

type TDeliveryLogContext = ReturnType<typeof getDeliveryLogContext>;

type TDeliveryTarget = {
  url: string;
  secret: string | null;
  triggers: string[];
  surveyIds: string[];
};

const loadDeliveryTarget = async (
  data: TWebhookDeliveryJobData,
  context: JobExecutionContext,
  logContext: TDeliveryLogContext
): Promise<TDeliveryTarget | null> => {
  try {
    // Scoped by workspace in the query rather than checked afterwards: a webhook id paired with the
    // wrong workspace then reads as absent instead of handing back another workspace's URL and signing
    // secret. Our own fan-out always pairs them correctly, so this guards stale or malformed job data.
    return await prisma.webhook.findFirst({
      where: { id: data.webhookId, workspaceId: data.workspaceId },
      select: { url: true, secret: true, triggers: true, surveyIds: true },
    });
  } catch (error) {
    // Counted like any other failed attempt: a database outage stops deliveries just as effectively as a
    // dead receiver, and a failure-rate alert that ignores it would stay green through the outage.
    recordWebhookDeliveryOutcome({ outcome: "load_failed", event: data.event });

    // Same last-attempt split as the delivery path below. A load failure on the final attempt drops the
    // event exactly like an exhausted HTTP retry does, so it has to emit the message the Job Runner
    // troubleshooting table tells operators to grep for — otherwise the one loss caused by our own
    // database is the only one that never announces itself.
    const failureLogContext = {
      ...logContext,
      err: error,
      outcome: "load_failed",
      reason: "the webhook could not be read from the database",
    };

    if (context.attempt >= context.maxAttempts) {
      logger.error(failureLogContext, "Webhook delivery failed; retries exhausted");
    } else if (isDatabasePoolExhaustionError(error)) {
      logger.warn(failureLogContext, "Webhook delivery hit database pool exhaustion and will be retried");
    } else {
      logger.error(failureLogContext, "Webhook delivery could not load the webhook and will be retried");
    }
    throw error;
  }
};

/**
 * A webhook still receives an event only while it is subscribed to it. The pipeline job matched
 * `triggers`/`surveyIds` when it fanned out; re-checking here means a webhook the user unsubscribed or
 * re-scoped while this delivery was queued or retrying gets nothing.
 */
const isStillSubscribed = (target: TDeliveryTarget, data: TWebhookDeliveryJobData): boolean =>
  target.triggers.includes(data.event) &&
  (target.surveyIds.length === 0 || target.surveyIds.includes(data.surveyId));

/** Check stored visibility at delivery time, including before graph readiness. */
const isSurveyStillOutboundVisible = async (surveyId: string): Promise<boolean> => {
  const survey = await prisma.survey.findUnique({
    where: { id: surveyId },
    select: surveyOutboundVisibilitySelect,
  });
  // Fail closed on a deleted survey: its queued payload may belong to one restricted before deletion,
  // and `Webhook.surveyIds` is not a foreign key, so the webhook still looks subscribed.
  return survey !== null && isSurveyOutboundAllowed(survey);
};

type TDeliveryAttempt = { kind: "completed"; statusCode: number } | { kind: "threw"; error: unknown };

const attemptDelivery = async (
  target: TDeliveryTarget,
  data: TWebhookDeliveryJobData
): Promise<TDeliveryAttempt> => {
  try {
    const { statusCode } = await sendSignedWebhookRequest({
      url: target.url,
      secret: target.secret,
      body: buildWebhookDeliveryBody(data),
      // Fixed at fan-out time from the pipeline job's id: identical on every attempt of this job, so
      // receivers can dedupe retries by `webhook-id` exactly as before the fan-out.
      messageId: data.webhookMessageId,
    });
    return { kind: "completed", statusCode };
  } catch (error) {
    return { kind: "threw", error };
  }
};

type TClassifiedFailure = {
  outcome: Extract<TWebhookDeliveryOutcome, "retryable_failure" | "permanent_failure">;
  reason: string;
  cause?: unknown;
};

const classifyFailure = (attempt: TDeliveryAttempt): TClassifiedFailure => {
  if (attempt.kind === "completed") {
    return isRetryableStatus(attempt.statusCode)
      ? { outcome: "retryable_failure", reason: `receiver responded with status ${attempt.statusCode}` }
      : {
          outcome: "permanent_failure",
          reason: `receiver rejected the request with status ${attempt.statusCode}`,
        };
  }

  const { error } = attempt;
  // Order matters: the DNS subclass is transient and must be matched before its InvalidInputError base.
  if (error instanceof WebhookDnsResolutionError) {
    return { outcome: "retryable_failure", reason: error.message, cause: error };
  }
  if (error instanceof InvalidInputError) {
    return { outcome: "permanent_failure", reason: error.message, cause: error };
  }
  if (error instanceof WebhookDeliveryTimeoutError) {
    return { outcome: "retryable_failure", reason: error.message, cause: error };
  }
  return {
    outcome: "retryable_failure",
    reason: error instanceof Error ? error.message : "unknown network error",
    cause: error,
  };
};

/**
 * Delivers one response event to one webhook. Enqueued by the response pipeline job, one job per
 * matching webhook, with its own retry budget (`WEBHOOK_DELIVERY_JOB_OPTIONS`).
 *
 * Outcome per attempt, in order of evaluation:
 * - the webhook row cannot be read → rethrow so BullMQ retries (`load_failed`)
 * - webhook row gone, or not this workspace's → complete (`skipped_deleted`); unsubscribed or re-scoped →
 *   complete (`skipped_rescoped`)
 * - 2xx → complete (`delivered`)
 * - SSRF/URL policy rejection or a 4xx other than 408/429 → `UnrecoverableError` (`permanent_failure`)
 * - anything else (network, timeout, DNS, 3xx, 408, 429, 5xx) → throw so BullMQ retries (`retryable_failure`)
 *
 * Every attempt emits exactly one outcome log line and one metric sample. Log context is scalar ids and
 * the URL's host only — webhook URLs routinely carry capability tokens, and the payload carries a survey
 * response, so neither may appear in a log line.
 */
export const processWebhookDeliveryJob: JobHandler<TWebhookDeliveryJobData> = async (data, context) => {
  const logContext = getDeliveryLogContext(data, context);

  const target = await loadDeliveryTarget(data, context, logContext);

  if (!target) {
    logger.info({ ...logContext, outcome: "skipped_deleted" }, "Webhook delivery skipped: webhook deleted");
    recordWebhookDeliveryOutcome({ outcome: "skipped_deleted", event: data.event });
    return;
  }

  if (!isStillSubscribed(target, data)) {
    logger.info(
      { ...logContext, outcome: "skipped_rescoped", webhookUrlHost: getWebhookUrlHost(target.url) },
      "Webhook delivery skipped: webhook no longer subscribed to this event"
    );
    recordWebhookDeliveryOutcome({ outcome: "skipped_rescoped", event: data.event });
    return;
  }

  // ENG-3283: the survey may have been restricted after this delivery was enqueued (or while it
  // was retrying). The pipeline checked at fan-out; this closes the window up to the request itself.
  if (!(await isSurveyStillOutboundVisible(data.surveyId))) {
    logger.info(
      { ...logContext, outcome: "skipped_not_visible", webhookUrlHost: getWebhookUrlHost(target.url) },
      "Webhook delivery skipped: survey is no longer visible to the whole workspace"
    );
    recordWebhookDeliveryOutcome({ outcome: "skipped_not_visible", event: data.event });
    return;
  }

  const startedAt = Date.now();
  const attempt = await attemptDelivery(target, data);
  const durationMs = Date.now() - startedAt;
  const statusCode = attempt.kind === "completed" ? attempt.statusCode : undefined;
  const attemptLogContext = {
    ...logContext,
    durationMs,
    statusCode,
    webhookUrlHost: getWebhookUrlHost(target.url),
  };

  if (attempt.kind === "completed" && isSuccessStatus(attempt.statusCode)) {
    logger.info({ ...attemptLogContext, outcome: "delivered" }, "Webhook delivered");
    recordWebhookDeliveryOutcome({ outcome: "delivered", event: data.event, statusCode, durationMs });
    return;
  }

  const failure = classifyFailure(attempt);
  recordWebhookDeliveryOutcome({ outcome: failure.outcome, event: data.event, statusCode, durationMs });

  if (failure.outcome === "permanent_failure") {
    logger.error(
      { ...attemptLogContext, err: failure.cause, outcome: failure.outcome, reason: failure.reason },
      "Webhook delivery failed permanently"
    );
    throw new UnrecoverableError(`Webhook ${data.webhookId} delivery failed permanently: ${failure.reason}`);
  }

  const willRetry = context.attempt < context.maxAttempts;
  const failureLogContext = {
    ...attemptLogContext,
    err: failure.cause,
    outcome: failure.outcome,
    reason: failure.reason,
  };
  if (willRetry) {
    logger.warn(failureLogContext, "Webhook delivery failed; retry scheduled");
  } else {
    logger.error(failureLogContext, "Webhook delivery failed; retries exhausted");
  }
  throw new Error(`Webhook ${data.webhookId} delivery failed: ${failure.reason}`);
};
