import "server-only";
import { prisma } from "@formbricks/database";
import { Prisma } from "@formbricks/database/prisma";
import { logger } from "@formbricks/logger";
import type { TCalBookingsByQuestionId } from "@formbricks/types/cal-booking";
import type { TEmbeddedValueResponse } from "@formbricks/types/embedded-data-resolver";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import type {
  TResponse,
  TResponseData,
  TResponseDataValue,
  TResponseMeta,
  TResponseOutcome,
  TResponseTtc,
  TResponseVariables,
} from "@formbricks/types/responses";
import type { InvalidParam } from "@/app/api/v3/lib/response";
import { sendToPipeline } from "@/app/lib/pipelines";
import { inlineSurveyEmbeddedFields } from "@/lib/embedded-data/survey-fields";
import { applyAnonymizePolicy } from "@/lib/response/anonymize";
import { calBookingsForAnswers } from "@/lib/response/cal-bookings";
import { getUniqueConstraintFields, isUniqueConstraintError } from "@/lib/utils/prisma-constraint";
import { drainDeletionCleanups } from "@/modules/deletion-cleanup/lib/drain";
import {
  evaluateResponseQuotas,
  loadQuotaEvaluationContext,
} from "@/modules/ee/quotas/lib/evaluation-service";
import { enqueueReplacedSignatureFileCleanup } from "@/modules/storage/lib/replaced-signature-files";
import {
  type TOutcomeScope,
  type TV3OutcomeChange,
  enqueueOutcomeCleanup,
  outcomeScopeWhere,
  writeResponsesOutcomeInTx,
} from "./outcome-write";
import { narrowToPublishableValue } from "./resources";
import { type TV3ResponseSurveyRow, v3ResponseReadSelect, v3ResponseSurveySelect } from "./service";
import type { TV3VariableWrites } from "./write-plan";

/**
 * The database half of the v3 response writes.
 *
 * Split from `service.ts` rather than appended to it because the two answer different questions: that
 * file is about reading a response without leaving its workspace, this one is about the ordering a
 * write has to respect. They share the selects and nothing else.
 *
 * Three orderings here are load-bearing and none of them is the obvious one:
 *
 * 1. **Reference checks run inside the transaction**, against the same snapshot the write uses. A
 *    `displayId` checked before the transaction can be claimed by a concurrent create in between.
 * 2. **Quota evaluation runs after the row exists**, in the same transaction, because a `reserved`
 *    quota operand resolves against the persisted row (ENG-1840) — and because it may itself flip
 *    `finished` to `true`.
 * 3. **Pipeline dispatch runs after commit**, and its `finished` comes from the row that was read
 *    back, never from the request body. A dispatch inside the transaction emits an event for a
 *    response a rollback then removes.
 */

/**
 * The survey a write is validated against: the read's select plus the three things only a write
 * needs. `endings` and `languages` back the two 422s that need no database of their own, and
 * `isAnonymizeResponsesEnabled` is what stops a caller writing submission context onto a survey
 * whose author turned anonymization on.
 */
export const v3WriteSurveySelect = {
  ...v3ResponseSurveySelect,
  questions: true,
  endings: true,
  isAnonymizeResponsesEnabled: true,
} satisfies Prisma.SurveySelect;

export type TV3WriteSurveyRow = Prisma.SurveyGetPayload<{ select: typeof v3WriteSurveySelect }> &
  Pick<TV3ResponseSurveyRow, "embeddedFields">;

/**
 * Resolve the survey a create is scoped by, **unscoped on purpose**.
 *
 * Same shape as `getResponseWorkspaceId`, and safe for the same reason: the caller feeds the
 * workspace straight into `requireV3WorkspaceAccess` and answers one 403 whether the survey is
 * missing or belongs to someone else. Resolving the scope from the survey rather than from a
 * client-supplied `workspaceId` is what makes it unforgeable.
 */
export async function getSurveyForV3Write(surveyId: string): Promise<TV3WriteSurveyRow | null> {
  const survey = await prisma.survey.findUnique({
    where: { id: surveyId },
    select: v3WriteSurveySelect,
  });

  return survey ? { ...survey, embeddedFields: inlineSurveyEmbeddedFields(survey) } : null;
}

/**
 * What a write reads back, and why it is not the read select.
 *
 * The row has two consumers with different needs: the serializer, which wants exactly what a `GET`
 * returns, and the pipeline payload, which is Zod-parsed against `ZResponse` in-request and fails on
 * a partial shape. Reading once with the union is a query cheaper than reading twice, and it is the
 * only way the two can never disagree about what was persisted.
 */
export const v3WriteReadbackSelect = {
  ...v3ResponseReadSelect,
  contactAttributes: true,
  tags: {
    select: {
      tag: { select: { id: true, createdAt: true, updatedAt: true, name: true, workspaceId: true } },
    },
  },
} satisfies Prisma.ResponseSelect;

export type TV3WriteReadbackRow = Prisma.ResponseGetPayload<{ select: typeof v3WriteReadbackSelect }>;

/**
 * The columns quota evaluation needs off the row it just wrote.
 *
 * Not a convenience: `evaluateResponseQuotas` builds the `reserved` operand map with
 * `buildServerEmbeddedValues`, whose catalog accessors read `meta.country`, `meta.url`,
 * `meta.userAgent.browser`, `createdAt`/`updatedAt` and `ttc` off this row. Every accessor is
 * wrapped in a `try`/`catch` that answers `undefined`, so a row missing those columns does not
 * fail — it silently resolves every reserved operand as unset, and a quota conditioned on one of
 * them counts nothing. v1 and v2 hand over the full row, so a narrower select here would make v3
 * the one write path where such a quota stops counting, with nothing logged.
 *
 * Shaped so `toQuotaEvaluationRow` can build a `TEmbeddedValueResponse` out of it without an escape
 * hatch — which is what makes a future narrowing of this select a build failure rather than a quota
 * that quietly stops matching.
 */
const v3QuotaEvaluationSelect = {
  id: true,
  surveyId: true,
  createdAt: true,
  updatedAt: true,
  finished: true,
  language: true,
  data: true,
  variables: true,
  ttc: true,
  meta: true,
} satisfies Prisma.ResponseSelect;

/**
 * Narrow the written row to the slice quota evaluation reads, field by field.
 *
 * Written out rather than cast wholesale so the compiler is the guard: every field
 * `TEmbeddedValueResponse` declares has to come from a column `v3QuotaEvaluationSelect` asks for, and
 * narrowing that select stops being a silent behaviour change and becomes a build failure. The casts
 * are confined here because Prisma types the four JSON columns as `JsonValue`; they are the shapes
 * the write itself persisted a few lines earlier.
 */
const toQuotaEvaluationRow = (
  row: Prisma.ResponseGetPayload<{ select: typeof v3QuotaEvaluationSelect }>
): TEmbeddedValueResponse => ({
  id: row.id,
  surveyId: row.surveyId,
  createdAt: row.createdAt,
  updatedAt: row.updatedAt,
  finished: row.finished,
  language: row.language,
  data: row.data as TResponseData,
  variables: row.variables as TResponseVariables,
  ttc: row.ttc as TResponseTtc,
  meta: row.meta as TResponseMeta,
});

/** Read back a written response, scoped. `null` means it was removed between the write and the read. */
export async function readbackV3Response(
  responseId: string,
  { workspaceId }: { workspaceId: string }
): Promise<TV3WriteReadbackRow | null> {
  return prisma.response.findFirst({
    where: { id: responseId, survey: { workspaceId } },
    select: v3WriteReadbackSelect,
  });
}

/**
 * Resolve the contact a create attributes the response to, and snapshot its attributes.
 *
 * Scoped to the caller's workspace, so "not in this workspace" and "does not exist" are one answer —
 * which is what keeps it from being an existence oracle for the tenant next door.
 */
async function checkContact(
  tx: Prisma.TransactionClient,
  workspaceId: string,
  contactId: string
): Promise<{ issue?: InvalidParam; contactAttributes?: Prisma.JsonValue }> {
  const contact = await tx.contact.findFirst({
    where: { id: contactId, workspaceId },
    select: { id: true, attributes: { select: { value: true, attributeKey: { select: { key: true } } } } },
  });

  if (!contact) {
    return {
      issue: {
        name: "contactId",
        reason: "No contact with this id exists in this workspace.",
        code: "invalid_reference",
      },
    };
  }

  // Snapshotted at create time, exactly as v1 and v2 do. v3 never publishes it, but the pipeline
  // reads `contactAttributes.userId` to identify the respondent to integrations, and an export
  // written months later cannot reconstruct what the attributes were on the day.
  return {
    contactAttributes: Object.fromEntries(
      contact.attributes.map(({ attributeKey, value }) => [attributeKey.key, value])
    ),
  };
}

/** A display belongs to one survey and backs at most one response. Both halves are checked here. */
async function checkDisplay(
  tx: Prisma.TransactionClient,
  surveyId: string,
  displayId: string,
  excludeResponseId?: string
): Promise<InvalidParam | null> {
  const display = await tx.display.findFirst({
    where: { id: displayId, surveyId },
    select: { id: true, response: { select: { id: true } } },
  });

  if (!display) {
    return {
      name: "displayId",
      reason: "No display with this id exists for this survey.",
      code: "invalid_reference",
    };
  }

  if (display.response && display.response.id !== excludeResponseId) {
    return {
      name: "displayId",
      reason: "This display already backs another response.",
      code: "duplicate_identifier",
    };
  }

  return null;
}

/** Single-use ids are unique per survey; the index enforces it, this reports it as the caller's. */
async function checkSingleUseId(
  tx: Prisma.TransactionClient,
  surveyId: string,
  singleUseId: string,
  excludeResponseId?: string
): Promise<InvalidParam | null> {
  const taken = await tx.response.findFirst({
    where: { singleUseId, surveyId, id: { not: excludeResponseId } },
    select: { id: true },
  });

  if (!taken) return null;

  return {
    name: "singleUseId",
    reason: "This single-use id has already been used for this survey.",
    code: "duplicate_identifier",
  };
}

/** One query for the whole set, then one issue per id that did not come back. */
async function checkTags(
  tx: Prisma.TransactionClient,
  workspaceId: string,
  tagIds: string[]
): Promise<InvalidParam[]> {
  const found = await tx.tag.findMany({ where: { id: { in: tagIds }, workspaceId }, select: { id: true } });
  const foundIds = new Set(found.map((tag) => tag.id));

  return tagIds
    .filter((tagId) => !foundIds.has(tagId))
    .map((tagId) => ({
      name: "tags",
      reason: `No tag with id '${tagId}' exists in this workspace.`,
      code: "invalid_reference" as const,
      identifier: tagId,
    }));
}

/**
 * The reference checks that need the database, run against the transaction's own snapshot.
 *
 * Every one of these is a 422 rather than a 404: the body is well-formed and the conflict is with
 * stored state. They are also all scoped to the workspace the caller is already authorized for, so
 * none of them can report on a resource outside it.
 *
 * Exported for `POST /api/v3/responses/validate`, which runs them against `prisma` rather than a
 * transaction. That is the honest dry run: outside a transaction these answer about the state now
 * rather than the state a write would see, which is exactly the guarantee a validate can offer.
 */
export async function collectReferenceIssues(
  tx: Prisma.TransactionClient,
  {
    workspaceId,
    surveyId,
    contactId,
    displayId,
    singleUseId,
    tagIds,
    excludeResponseId,
  }: {
    workspaceId: string;
    surveyId: string;
    contactId?: string;
    displayId?: string;
    singleUseId?: string;
    tagIds?: string[];
    excludeResponseId?: string;
  }
): Promise<{ issues: InvalidParam[]; contactAttributes: Prisma.JsonValue | undefined }> {
  const issues: InvalidParam[] = [];
  let contactAttributes: Prisma.JsonValue | undefined;

  if (contactId) {
    const result = await checkContact(tx, workspaceId, contactId);
    if (result.issue) issues.push(result.issue);
    contactAttributes = result.contactAttributes;
  }

  if (displayId) {
    const issue = await checkDisplay(tx, surveyId, displayId, excludeResponseId);
    if (issue) issues.push(issue);
  }

  if (singleUseId) {
    const issue = await checkSingleUseId(tx, surveyId, singleUseId, excludeResponseId);
    if (issue) issues.push(issue);
  }

  if (tagIds && tagIds.length > 0) {
    issues.push(...(await checkTags(tx, workspaceId, tagIds)));
  }

  return { issues, contactAttributes };
}

/**
 * A unique-constraint violation the pre-checks above lost a race to.
 *
 * Mapped to the same 422 the pre-check would have produced rather than to the generic 409, because
 * `POST`/`PATCH` do not document a 409 and a race must not be distinguishable from losing the check
 * outright.
 *
 * The columns come from `getUniqueConstraintFields`, which is the one place in the codebase allowed
 * to touch Prisma's `error.meta` — a shape Prisma states is not public API and which differs by
 * engine and version. Reading `meta.target` directly, as the obvious version of this does, matches
 * nothing on this repo: under Prisma 7 + `@prisma/adapter-pg` that key is absent, and since 7.10 the
 * adapter reports only the constraint name (`meta.driverAdapterError.cause.constraint.index`), which
 * the helper resolves back to columns. The obvious version therefore returns `null` for every real
 * race, and the caller rethrows into the generic 500.
 *
 * Mapping the race here, rather than letting it fall through to the generic 500, also keeps the raw
 * error out of the logs: the 500 branch logs it under `err`, and pino's error serializer copies every
 * enumerable property of `meta.driverAdapterError.cause`. `prisma-constraint.ts` warns against
 * surfacing those fields to a response *or a log*, and reading only the structured column list is how
 * this path honours it.
 */
function raceIssuesFromUniqueViolation(error: unknown): InvalidParam[] | null {
  if (!isUniqueConstraintError(error)) return null;

  const columns = getUniqueConstraintFields(error);

  if (columns.includes("singleUseId")) {
    return [
      {
        name: "singleUseId",
        reason: "This single-use id has already been used for this survey.",
        code: "duplicate_identifier",
      },
    ];
  }

  if (columns.includes("displayId")) {
    return [
      {
        name: "displayId",
        reason: "This display already backs another response.",
        code: "duplicate_identifier",
      },
    ];
  }

  return null;
}

/**
 * A scoped write that matched no row.
 *
 * The update's `where` carries `survey: { workspaceId }`, so P2025 means the response is gone or was
 * never this caller's — the same fact a pre-flight rejection establishes, and it has to answer the
 * same 403. `mapV3ThrownError` does not map raw Prisma errors, so without this translation the
 * promise in the scoped-update comment is not kept and the caller gets a 500 instead.
 *
 * Since the reference `connect`s became scoped too, P2025 also covers a contact, display or tag that
 * stopped matching its scope between the pre-flight check and the write.
 *
 * That answer is a 403, and it is **not** the body the routine case gets: a foreign reference caught
 * by the pre-flight is a 422 naming the field, which is what the contract documents. An earlier
 * version of this comment claimed the two matched — they do not, and the difference is worth being
 * precise about, because it is a documented-status divergence rather than a cosmetic one.
 *
 * It is still the right answer. The divergence is reachable only by losing a race — the reference was
 * in scope when checked and out of scope by the time the row was written — and in that state the
 * server cannot honestly say which field is at fault without re-reading and guessing. 403 with the
 * uniform body says the least, and says nothing a foreign-reference 403 elsewhere does not already
 * say. Which reference lost is recoverable from the logged Prisma error, and deliberately not from
 * the response.
 */
function rethrowScopedNotFound(error: unknown): void {
  if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
    // No id in the message: it is already correlated by requestId, and the operation keeps it out of
    // the body.
    throw new ResourceNotFoundError("Response", null);
  }
}

/** Either the row a write persisted, or the reference failures that stopped it. */
export type TV3WriteOutcome = { ok: true; responseId: string } | { ok: false; issues: InvalidParam[] };

export type TV3CreateResponsePersist = {
  workspaceId: string;
  survey: TV3WriteSurveyRow;
  finished: boolean;
  data: TResponseData;
  variables: TV3VariableWrites;
  ttc: TResponseTtc;
  meta: TResponseMeta | undefined;
  tagIds: string[];
  endingId: string | null | undefined;
  language: string | null | undefined;
  contactId: string | undefined;
  displayId: string | undefined;
  singleUseId: string | undefined;
};

/**
 * Create one response, its tags and its quota links in a single transaction.
 *
 * The quota step can flip `finished` to `true` on the row it just counted, so nothing downstream may
 * assume the request body's `finished` is what got stored — the caller reads the row back.
 */
export async function createScopedResponse(input: TV3CreateResponsePersist): Promise<TV3WriteOutcome> {
  const { workspaceId, survey, meta, tagIds, contactId, displayId, singleUseId } = input;
  // `TagsOnResponses` is keyed on (responseId, tagId), so a repeated id is a composite-primary-key
  // violation rather than a redundant write. The contract calls `tags` a set; this is what makes it
  // one. Create already refuses duplicates at the schema, but the patch deliberately allows them.
  const uniqueTagIds = [...new Set(tagIds)];
  // Already resolved to one of the survey's own declared codes by `resolveV3WriteLanguage`, so it is
  // deliberately not canonicalized again here — that is what would push it out of the survey's set.
  const language = input.language ?? null;
  // Read before the transaction opens — see `TQuotaEvaluationContext`.
  const quotaContext = await loadQuotaEvaluationContext(survey.id);

  try {
    return await prisma.$transaction(async (tx) => {
      const { issues, contactAttributes } = await collectReferenceIssues(tx, {
        workspaceId,
        surveyId: survey.id,
        contactId,
        displayId,
        singleUseId,
        tagIds,
      });

      if (issues.length > 0) {
        return { ok: false as const, issues };
      }

      const created = await tx.response.create({
        data: {
          survey: { connect: { id: survey.id } },
          // Every `connect` below carries its own scope, not just an id. The checks above already
          // refused a foreign reference with a 422 naming the field, so this is the second layer:
          // it re-states the tenant predicate inside the write, where it reaches the SQL and rolls
          // the whole create back with P2025 on a non-match. That closes the window between check
          // and write, and — more to the point — it keeps holding if someone later moves, reorders
          // or forgets the checks. ENG-825, ENG-827 and ENG-1923 were all this shape.
          //
          // `display` is scoped by survey rather than workspace, and by `response: null`: Display has
          // no `workspaceId`, and workspace-only scoping would lose the cross-survey check ENG-825
          // was about. Verified against a real database — a foreign `surveyId` and an already-claimed
          // display both raise P2025 and leave no row.
          ...(displayId
            ? { display: { connect: { id: displayId, surveyId: survey.id, response: null } } }
            : {}),
          ...(contactId
            ? {
                contact: { connect: { id: contactId, workspaceId } },
                contactAttributes: contactAttributes ?? Prisma.JsonNull,
              }
            : {}),
          finished: input.finished,
          data: input.data,
          variables: input.variables,
          ttc: input.ttc,
          // "Anonymize responses" is a property of the survey, not of the door the response arrived
          // through, so it is applied here rather than trusted from the caller.
          meta: applyAnonymizePolicy(meta, survey.isAnonymizeResponsesEnabled) ?? {},
          language,
          endingId: input.endingId ?? null,
          singleUseId: singleUseId ?? null,
          ...(uniqueTagIds.length > 0
            ? {
                tags: {
                  create: uniqueTagIds.map((tagId) => ({
                    tag: { connect: { id: tagId, workspaceId } },
                  })),
                },
              }
            : {}),
        },
        select: v3QuotaEvaluationSelect,
      });

      await evaluateResponseQuotas({
        surveyId: survey.id,
        responseId: created.id,
        data: created.data as TResponseData,
        variables: created.variables as Record<string, TResponseDataValue>,
        language: language ?? "default",
        responseFinished: created.finished,
        // The row as persisted, so `reserved` quota operands resolve (ENG-1840).
        response: toQuotaEvaluationRow(created),
        tx,
        quotaContext,
      });

      return { ok: true as const, responseId: created.id };
    });
  } catch (error) {
    const raceIssues = raceIssuesFromUniqueViolation(error);
    if (raceIssues) return { ok: false, issues: raceIssues };

    rethrowScopedNotFound(error);
    throw error;
  }
}

export type TV3UpdateResponsePersist = {
  responseId: string;
  workspaceId: string;
  survey: TV3WriteSurveyRow;
  /** Only the keys the payload actually carried — an absent one must not be written as `undefined`. */
  patch: {
    finished?: boolean;
    endingId?: string | null;
    language?: string | null;
    /** `null` restores — see `ResponseOutcome`. */
    outcome?: TResponseOutcome | null;
    data?: TResponseData;
    variables?: TV3VariableWrites;
    tagIds?: string[];
    /**
     * Server-derived, never caller-supplied: `ttc` is create-only for a caller, but `_total` is a
     * derivation the shared update service performs on any write that finishes a response.
     */
    ttc?: TResponseTtc;
  };
};

/**
 * Apply a patch to one response, scoped, in a single transaction.
 *
 * `tags` is replace-the-set rather than add: the contract defines it as the complete set, so the
 * join rows are cleared and rewritten. Everything else is set only when the payload carried it —
 * spreading `undefined` into a Prisma `update` is the difference between "leave it" and "null it"
 * for the nullable columns, and `endingId` and `language` are both nullable.
 */
export async function updateScopedResponse({
  responseId,
  workspaceId,
  survey,
  patch,
}: TV3UpdateResponsePersist): Promise<TV3WriteOutcome> {
  // Read before the transaction opens — see `TQuotaEvaluationContext`.
  const quotaContext = await loadQuotaEvaluationContext(survey.id);

  try {
    const written = await prisma.$transaction(async (tx) => {
      const { issues } = await collectReferenceIssues(tx, {
        workspaceId,
        surveyId: survey.id,
        tagIds: patch.tagIds,
        excludeResponseId: responseId,
      });

      if (issues.length > 0) {
        return { ok: false as const, issues };
      }

      // `data` replaces the stored data, so the image of a signature this patch drops or swaps is read off
      // the row as it is inside this transaction, scoped like the update. Skipped without data.
      const previous =
        patch.data === undefined
          ? null
          : await tx.response.findFirst({
              where: { id: responseId, survey: { workspaceId } },
              select: { data: true, calBookings: true },
            });

      // Read in the transaction that writes it, so the change the cleanup follows is the change made here.
      const outcomeChanged =
        patch.outcome !== undefined &&
        (await readStoredOutcome(tx, responseId, workspaceId)) !== patch.outcome;

      // Scoped `where`, never a bare id — a response outside the workspace matches nothing and
      // Prisma raises P2025, which the operation renders as the same 403 as a pre-flight rejection.
      // `data` replaces the stored data, so a booking whose answer is no longer "booked" goes with it.
      const prunedCalBookings = calBookingsAfterReplace(previous?.calBookings, patch.data);

      const updated = await tx.response.update({
        where: { id: responseId, survey: { workspaceId } },
        data: {
          ...(prunedCalBookings && { calBookings: prunedCalBookings }),
          ...(patch.finished === undefined ? {} : { finished: patch.finished }),
          ...(patch.endingId === undefined ? {} : { endingId: patch.endingId }),
          ...(patch.language === undefined ? {} : { language: patch.language }),
          ...(patch.outcome === undefined ? {} : { outcome: patch.outcome }),
          ...(patch.data === undefined ? {} : { data: patch.data }),
          ...(patch.ttc === undefined ? {} : { ttc: patch.ttc }),
          ...(patch.variables === undefined ? {} : { variables: patch.variables }),
          ...(patch.tagIds === undefined
            ? {}
            : {
                tags: {
                  deleteMany: {},
                  // Deduplicated — see the note in `createScopedResponse`.
                  // Scoped like the create path: the id alone would let a tag that left the
                  // workspace between check and write still attach.
                  create: [...new Set(patch.tagIds)].map((tagId) => ({
                    tag: { connect: { id: tagId, workspaceId } },
                  })),
                },
              }),
        },
        select: v3QuotaEvaluationSelect,
      });

      if (previous) {
        // After the write, in its transaction: a patch that rolls back queues nothing.
        await enqueueReplacedSignatureFileCleanup(
          tx,
          { surveyId: survey.id, previousData: previous.data, nextData: updated.data },
          { bestEffort: false }
        );
      }

      // Evaluated on every patch, not only on one that finishes the response. For a quota with
      // `countPartialSubmissions: false` the link row is written only once the response is finished,
      // so a create-only evaluation silently under-counts every response that finishes later.
      await evaluateResponseQuotas({
        surveyId: survey.id,
        responseId: updated.id,
        data: updated.data as TResponseData,
        variables: updated.variables as Record<string, TResponseDataValue>,
        language: updated.language ?? "default",
        responseFinished: updated.finished,
        response: toQuotaEvaluationRow(updated),
        tx,
        quotaContext,
      });

      const { drainNowIds } = outcomeChanged
        ? await enqueueOutcomeCleanup(tx, workspaceId, [{ id: updated.id, surveyId: survey.id }])
        : { drainNowIds: [] };

      return { ok: true as const, responseId: updated.id, drainNowIds };
    });
    if (!written.ok) return written;

    await drainOutcomeCleanups(written.drainNowIds, workspaceId);
    return { ok: true, responseId: written.responseId };
  } catch (error) {
    const raceIssues = raceIssuesFromUniqueViolation(error);
    if (raceIssues) return { ok: false, issues: raceIssues };

    rethrowScopedNotFound(error);
    throw error;
  }
}

/**
 * The stored Cal bookings left once `data` replaces the stored data, or `undefined` when none is dropped (so
 * the column is not written). A booking whose answer is no longer "booked" goes with it.
 */
const calBookingsAfterReplace = (
  stored: TCalBookingsByQuestionId | null | undefined,
  data: TResponseData | undefined
): TCalBookingsByQuestionId | undefined => {
  if (!stored || !data) return undefined;
  const kept = calBookingsForAnswers(stored, data);
  return Object.keys(kept).length === Object.keys(stored).length ? undefined : kept;
};

const readStoredOutcome = async (
  tx: Prisma.TransactionClient,
  responseId: string,
  workspaceId: string
): Promise<TResponseOutcome | null | undefined> =>
  (
    await tx.response.findFirst({
      where: { id: responseId, survey: { workspaceId } },
      select: { outcome: true },
    })
  )?.outcome;

/**
 * How long a request waits for the first attempt at the Hub cleanup. The Hub's client waits up to a minute
 * per attempt, so a Hub that accepts the connection and never answers would hold the request that much
 * longer for an outcome that is already committed (seen against the real Hub, ENG-6785). The drain keeps
 * running past this; it just stops being waited for, and its row backs off if it fails.
 */
export const INLINE_DRAIN_WAIT_MS = 5000;

/**
 * The first attempt at the Hub cleanup, straight after commit. A Hub outage, or any failure here, only
 * delays it to the drain job with its backoff: the outcome is already committed, so it must never fail the
 * request that set it, nor hold it for long.
 */
const drainOutcomeCleanups = async (drainNowIds: string[], workspaceId: string): Promise<void> => {
  if (drainNowIds.length === 0) return;
  let timer: ReturnType<typeof setTimeout> | undefined;
  const drain = drainDeletionCleanups({ ids: drainNowIds }).catch((error: unknown) => {
    logger.error(
      { err: error, workspaceId, responseCount: drainNowIds.length },
      "Deferred the Feedback Record cleanup of an outcome change to the drain job"
    );
  });
  try {
    await Promise.race([
      drain,
      new Promise<void>((resolve) => {
        timer = setTimeout(resolve, INLINE_DRAIN_WAIT_MS);
      }),
    ]);
  } finally {
    clearTimeout(timer);
  }
};

/**
 * Which of `ids` are in scope, and the survey each belongs to — what a batch authorizes against before it
 * writes anything. One query for up to a batch of ids; the caller checks one response per distinct survey.
 */
export async function listScopedResponseSurveyRefs(
  ids: string[],
  scope: TOutcomeScope
): Promise<{ id: string; surveyId: string }[]> {
  return prisma.response.findMany({
    where: outcomeScopeWhere(ids, scope),
    select: { id: true, surveyId: true },
  });
}

export type TV3BatchOutcomeResult = {
  /** Responses in scope, including those that already carried the outcome: a retry reports the same number. */
  matched: number;
  /** Only the responses whose outcome actually changed, with what it was — the audit trail and the events. */
  changes: TV3OutcomeChange[];
  /** The changed responses as the pipeline needs them, read back after commit. */
  rows: TV3WriteReadbackRow[];
};

/**
 * Set `outcome` on every response of `ids` that is in scope, in one transaction.
 *
 * Scope-filters rather than rejecting, like the batch delete: the workspace (and the caller's visible
 * surveys) sit in every statement's `where`, so a foreign or missing id matches nothing. Only responses
 * whose outcome differs are written — a retry, or a batch that overlaps an earlier one, neither churns
 * `updatedAt` nor re-fires `responseUpdated` for rows that did not change.
 *
 * The read-back runs after commit and is scoped the same way; a row that vanished in between simply
 * drops out of `rows`.
 */
export async function setScopedResponsesOutcome(
  ids: string[],
  outcome: TResponseOutcome | null,
  scope: TOutcomeScope
): Promise<TV3BatchOutcomeResult> {
  let matched = 0;
  let changes: TV3OutcomeChange[] = [];
  let drainNowIds: string[] = [];

  try {
    await prisma.$transaction(async (tx) => {
      ({ matched, changes, drainNowIds } = await writeResponsesOutcomeInTx(tx, ids, outcome, scope));
    });
  } catch (error) {
    rethrowScopedNotFound(error);
    throw error;
  }

  if (changes.length === 0) return { matched, changes, rows: [] };

  await drainOutcomeCleanups(drainNowIds, scope.workspaceId);

  const rows = await prisma.response.findMany({
    where: outcomeScopeWhere(
      changes.map(({ id }) => id),
      scope
    ),
    select: v3WriteReadbackSelect,
  });

  return { matched, changes, rows };
}

/**
 * Reshape a read-back row into the `TResponse` the pipeline is parsed against.
 *
 * Not cosmetic, and not optional. `enqueueResponsePipeline` Zod-parses its payload against
 * `ZResponse` **in-request**, and two of this row's fields are stored shapes rather than that shape:
 * `tags` arrives as join rows (`{ tag: … }[]`) where `ZResponse` wants `TTag[]`, and `contact`
 * carries an attribute row where it wants `{ id, userId }`. Handing the raw row over parses as a
 * failure, `sendToPipeline` throws, and because dispatch is deliberately non-fatal the request still
 * answers 201 — so the response is created and **no webhook, integration, follow-up or Hub ingestion
 * ever runs**, with nothing in the reply to say so. Found by smoke-testing a real create; a unit test
 * now parses this function's output against `ZResponse` so it cannot drift back.
 *
 * `data` is the third such field: a legacy row can hold a JSON `null` or a number array, which
 * `ZResponse` refuses and a `PATCH` keeps (the read withholds it, so leaving it out is not a
 * deletion). Only the value shape is filtered: an entry whose value is outside the published
 * shapes is left out of the payload, and every other entry — hidden-field values included, as the
 * pipeline has always carried them — passes through unchanged. Storage keeps the legacy value.
 */
export function toV3PipelineResponse(row: TV3WriteReadbackRow): TResponse {
  return {
    id: row.id,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    surveyId: row.surveyId,
    displayId: row.displayId,
    contact: row.contact
      ? {
          id: row.contact.id,
          // The snapshot taken at create time, not a live read: it is what the response was
          // attributed to, and it is the same source v1 and v2 hand the pipeline.
          ...((row.contactAttributes as Record<string, string> | null)?.userId
            ? { userId: (row.contactAttributes as Record<string, string>).userId }
            : {}),
        }
      : null,
    contactAttributes: (row.contactAttributes ?? null) as TResponse["contactAttributes"],
    finished: row.finished,
    endingId: row.endingId,
    data: Object.fromEntries(
      Object.entries((row.data ?? {}) as Record<string, unknown>).flatMap(([key, value]) => {
        const publishable = narrowToPublishableValue(value);
        return publishable === undefined ? [] : [[key, publishable] as const];
      })
    ),
    variables: (row.variables ?? {}) as TResponse["variables"],
    ttc: (row.ttc ?? {}) as TResponse["ttc"],
    tags: row.tags.map(({ tag }) => tag),
    meta: (row.meta ?? {}) as TResponse["meta"],
    singleUseId: row.singleUseId,
    language: row.language,
    outcome: row.outcome,
  };
}

/**
 * Emit the pipeline events for a committed write — after commit, and never fatally.
 *
 * **A queueing failure does not fail the request.** The row is already committed, so a 500 here
 * would tell a caller its write failed when it did not, and the retry that follows creates a second
 * response. A missed webhook is recoverable; a duplicated submission is not. `sendToPipeline`
 * rethrows on failure, which is why this wrapper exists at all.
 *
 * `finished` comes from the row that was read back rather than from the request: quota evaluation
 * can finish a response the caller submitted as partial, and that response has genuinely finished.
 */
export async function dispatchV3ResponsePipeline({
  event,
  workspaceId,
  surveyId,
  response,
  alsoFinished,
}: {
  event: "responseCreated" | "responseUpdated";
  workspaceId: string;
  surveyId: string;
  response: TV3WriteReadbackRow;
  alsoFinished: boolean;
}): Promise<void> {
  const payload = toV3PipelineResponse(response);

  const events: ("responseCreated" | "responseUpdated" | "responseFinished")[] = alsoFinished
    ? [event, "responseFinished"]
    : [event];

  for (const pipelineEvent of events) {
    try {
      await sendToPipeline({ event: pipelineEvent, workspaceId, surveyId, response: payload });
    } catch (error) {
      logger.error(
        { err: error, event: pipelineEvent, surveyId, workspaceId },
        "V3 response pipeline dispatch failed"
      );
    }
  }
}
