import { beforeEach, describe, expect, test, vi } from "vitest";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { requestEmailAuditErasureRequired } from "@/modules/email/lib/email-audit-maintenance";
import {
  deleteScopedResponse,
  deleteScopedResponses,
  getResponseWorkspaceId,
  getV3ResponseSurveys,
} from "./service";

vi.mock("server-only", () => ({}));
vi.mock("@/modules/email/lib/email-audit-maintenance", () => ({
  requestEmailAuditErasureRequired: vi.fn().mockResolvedValue(undefined),
}));

const {
  mockTxDelete,
  mockTxFindMany,
  mockTxDeleteMany,
  mockTxSurveyMany,
  mockTxDisplayDeleteMany,
  mockTxSurvey,
  mockFindFirst,
  mockTransaction,
  mockDeleteDisplay,
  mockReduceQuotas,
  mockDeleteFiles,
  mockSurveyFindMany,
  mockTxWorkspace,
  mockEnqueue,
  mockDrain,
} = vi.hoisted(() => ({
  mockTxDelete: vi.fn(),
  mockTxFindMany: vi.fn(),
  mockTxDeleteMany: vi.fn(),
  mockTxSurveyMany: vi.fn(),
  mockTxDisplayDeleteMany: vi.fn(),
  mockTxSurvey: vi.fn(),
  mockFindFirst: vi.fn(),
  mockTransaction: vi.fn(),
  mockDeleteDisplay: vi.fn(),
  mockReduceQuotas: vi.fn(),
  mockDeleteFiles: vi.fn(),
  mockSurveyFindMany: vi.fn(),
  mockTxWorkspace: vi.fn(),
  mockEnqueue: vi.fn(),
  mockDrain: vi.fn(),
}));

vi.mock("@formbricks/database", () => ({
  prisma: {
    response: { findFirst: mockFindFirst },
    survey: { findMany: mockSurveyFindMany },
    $transaction: mockTransaction,
  },
}));
vi.mock("@formbricks/database/prisma", () => ({
  Prisma: {
    PrismaClientKnownRequestError: class extends Error {
      code: string;
      constructor(message: string, code: string) {
        super(message);
        this.code = code;
      }
    },
  },
}));
vi.mock("@formbricks/logger", () => ({ logger: { error: vi.fn(), warn: vi.fn() } }));
vi.mock("@/lib/display/service", () => ({ deleteDisplay: mockDeleteDisplay }));
vi.mock("@/modules/ee/quotas/lib/quotas", () => ({ reduceQuotaLimits: mockReduceQuotas }));
vi.mock("@/modules/storage/lib/delete-response-files", () => ({ deleteResponseFileUrls: mockDeleteFiles }));
vi.mock("@/modules/deletion-cleanup/lib/enqueue", () => ({ enqueueResponsesDeletionCleanups: mockEnqueue }));
vi.mock("@/modules/deletion-cleanup/lib/drain", () => ({ drainDeletionCleanups: mockDrain }));
// The real collection rule, so the tests see which URLs a response's own survey id makes deletable;
// only the element-id lookup is pinned, to keep the survey fixtures free of upload elements.
vi.mock("@/modules/storage/utils", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@/modules/storage/utils")>()),
  getSurveyUploadElementIds: () => ({
    fileUpload: new Set(["screenshots"]),
    signature: new Set(["signature"]),
  }),
}));

const RESPONSE_ID = "clrsaaaaaaaaaaaaaaaaaaaa";
const SCOPE = { workspaceId: "ws_1" };

/**
 * Runs the callback with a tx whose `response.delete` and `survey.findUnique` are our spies, like a
 * real interactive transaction. The survey is a separate query rather than a join precisely so the
 * delete keeps raising P2025 — see the service's own note.
 */
const runTransaction = (result: unknown, survey: unknown = { blocks: [], questions: [] }) => {
  mockTxDelete.mockResolvedValue(result);
  mockTxSurvey.mockResolvedValue(survey);
  mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) =>
    fn({ response: { delete: mockTxDelete }, survey: { findUnique: mockTxSurvey } })
  );
};

const deletedRow = (over: Record<string, unknown> = {}) => ({
  id: RESPONSE_ID,
  finished: true,
  surveyId: "svy_1",
  data: {},
  meta: {},
  displayId: null,
  ...over,
});

describe("deleteScopedResponse", () => {
  beforeEach(() => vi.clearAllMocks());

  /**
   * The security core of the service. `Response` has no `workspaceId` column, so tenancy is only
   * expressible as `survey: { workspaceId }` — and it has to be in the `where` of the delete itself, not
   * a check before it. A bare-id delete with a prior ownership read has a window between the two and
   * relies on nobody ever calling the accessor directly.
   */
  test("scopes the delete by workspace, never by bare id", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockTxDelete).toHaveBeenCalledTimes(1);
    const { where } = mockTxDelete.mock.calls[0][0];
    expect(where).toStrictEqual({ id: RESPONSE_ID, survey: { workspaceId: "ws_1" } });
  });

  test("marks the deleted response for email copy erasure in the transaction", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(requestEmailAuditErasureRequired).toHaveBeenCalledWith(
      { responseId: RESPONSE_ID },
      expect.any(Object)
    );
  });

  test("rolls back when the email erasure request fails", async () => {
    runTransaction(deletedRow());
    vi.mocked(requestEmailAuditErasureRequired).mockRejectedValueOnce(new Error("audit unavailable"));

    await expect(deleteScopedResponse(RESPONSE_ID, SCOPE)).rejects.toThrow("audit unavailable");
    expect(mockDeleteFiles).not.toHaveBeenCalled();
  });

  /**
   * The file URLs live only inside `response.data`, so reading them after the delete returns nothing —
   * the delete's own select is the only place they can come from. The same select carries the scalars
   * the audit trail records, for the same reason: the row is gone afterwards.
   */
  test("captures the file data and the audit scalars in the delete's own select", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    const { select } = mockTxDelete.mock.calls[0][0];
    expect(select.data).toBe(true);
    // What the audit event records. Losing any of these silently thins the trail.
    for (const field of ["id", "createdAt", "finished", "surveyId", "ttc", "variables", "language"]) {
      expect(select[field]).toBe(true);
    }
  });

  /**
   * The audit event records this row, and `redactPII` matches exact key names — so `meta.ipAddress`
   * would reach the audit store in plaintext, and a workspace's own contact attributes would survive
   * wherever their key is not one of the standard ones. Both are named by this resource's contract as
   * never exposed in any view, and neither is read by anything here, so the select is the right place
   * to stop them. `contactId` and `surveyId` keep the record reviewable.
   */
  test("does not select the two fields the contract never exposes", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    const { select } = mockTxDelete.mock.calls[0][0];
    expect(select.meta).toBeUndefined();
    expect(select.contactAttributes).toBeUndefined();
    // Still identifiable for review, without carrying the respondent's identity.
    expect(select.contactId).toBe(true);
  });

  /**
   * Load-bearing, not stylistic. A `delete` whose select pulls a relation is compiled read-then-delete
   * on Prisma 7 and stops raising P2025 when the row is already gone, so a concurrent loser is told it
   * succeeded. The real-Postgres race in `service.integration.test.ts` measures that; this pins the
   * shape cheaply so the join cannot creep back in.
   */
  test("keeps the delete's select free of relations, and reads the survey separately", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    const { select } = mockTxDelete.mock.calls[0][0];
    const relations = Object.entries(select).filter(([, v]) => typeof v === "object" && v !== null);
    expect(relations).toStrictEqual([]);

    // Both shapes, matching v1/v2 and the helper's documented union — not just `blocks`.
    expect(mockTxSurvey).toHaveBeenCalledWith({
      where: { id: "svy_1" },
      select: { blocks: true, questions: true },
    });
  });

  /**
   * Regression guard, and the reason it is phrased as a never-call.
   *
   * `ResponseQuotaLink` is `onDelete: Cascade` and the repo's only fullness predicate is
   * `screenedInCount >= quota.limit` over those live rows, so the cascade already returns the capacity.
   * `reduceQuotaLimits` decrements `SurveyQuota.limit` — the customer's configured target — which
   * cancels the freed slot and ratchets the limit down irreversibly. The dashboard exposes that as an
   * explicit opt-in checkbox; an API delete must not do it silently.
   *
   * Asserted against the mock rather than the DB because the earlier version of this test asserted only
   * that the mock *was* called, which cannot observe the direction of the effect. The real-Postgres
   * counterpart in `service.integration.test.ts` measures the quota state itself.
   */
  test("never shrinks the configured quota limit", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockReduceQuotas).not.toHaveBeenCalled();
  });

  /**
   * A delete that does not record what it destroyed is not a reviewable audit trail. The survey join is
   * a means to the file cleanup, not part of the row, so it must not ride along into the audit payload.
   */
  test("returns the deleted row for the audit trail, without the survey join", async () => {
    runTransaction(deletedRow({ data: { q1: "answer" }, singleUseId: "sui_1" }));

    const returned = await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(returned).toStrictEqual({
      id: RESPONSE_ID,
      finished: true,
      surveyId: "svy_1",
      data: { q1: "answer" },
      meta: {},
      displayId: null,
      singleUseId: "sui_1",
    });
    expect(returned).not.toHaveProperty("survey");
  });

  test("deletes the linked display inside the same transaction", async () => {
    runTransaction(deletedRow({ displayId: "cldp_1" }));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteDisplay).toHaveBeenCalledWith("cldp_1", expect.anything());
  });

  /**
   * Ordering, asserted rather than assumed: inside the transaction a rollback would leave a live
   * response pointing at deleted objects. Both existing delete paths order it this way.
   */
  test("removes stored files only after the transaction commits", async () => {
    const order: string[] = [];
    mockTxDelete.mockResolvedValue(deletedRow({ data: { screenshots: ["https://s/a.png"] } }));
    mockTxSurvey.mockResolvedValue({ blocks: [], questions: [] });
    mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => {
      const out = await fn({ response: { delete: mockTxDelete }, survey: { findUnique: mockTxSurvey } });
      order.push("commit");
      return out;
    });
    mockDeleteFiles.mockImplementation(async () => void order.push("files"));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(order).toStrictEqual(["commit", "files"]);
    expect(mockDeleteFiles).toHaveBeenCalledWith(["https://s/a.png"], "ws_1");
  });

  // The answer of an upload element since deleted from the survey sits under an id no longer in the set.
  // Its key is filed under the response's own survey, which is what makes it this delete's to remove.
  test("removes an upload left by a removed element of the response's own survey", async () => {
    const ownFile = "/storage/ws_1/private/surveys/svy_1/elements/removed/a.png";
    runTransaction(deletedRow({ data: { removed: [ownFile] } }));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteFiles).toHaveBeenCalledWith([ownFile], "ws_1");
  });

  // A Signature answer is one URL string (ADR 0023); the element id decides it is a delete target.
  test("removes the signature image of the response's own survey and element", async () => {
    const ownSignature = "/storage/ws_1/private/surveys/svy_1/elements/signature/s--fid--abc.png";
    runTransaction(deletedRow({ data: { signature: ownSignature } }));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteFiles).toHaveBeenCalledWith([ownSignature], "ws_1");
  });

  test("removes the signature image left by an element since deleted from the survey", async () => {
    const orphan = "/storage/ws_1/private/surveys/svy_1/elements/removed-signature/s--fid--abc.png";
    runTransaction(deletedRow({ data: { "removed-signature": orphan } }));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteFiles).toHaveBeenCalledWith([orphan], "ws_1");
  });

  // Changing a Signature to Free text keeps the id, so the PNG sits under a live text element and is
  // still this response's to remove.
  test("removes the signature image of an element since retyped to Free text", async () => {
    const retyped = "/storage/ws_1/private/surveys/svy_1/elements/text/s--fid--abc.png";
    runTransaction(deletedRow({ data: { text: retyped } }));

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteFiles).toHaveBeenCalledWith([retyped], "ws_1");
  });

  test("never removes a signature URL from another survey or element, or one pasted into another text answer", async () => {
    runTransaction(
      deletedRow({
        data: {
          signature: "/storage/ws_1/private/surveys/svy_other/elements/signature/s--fid--abc.png",
          text: "/storage/ws_1/private/surveys/svy_1/elements/signature/s--fid--abc.png",
        },
      })
    );

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    expect(mockDeleteFiles).not.toHaveBeenCalled();
  });

  test("does not call storage at all when the response held no files", async () => {
    runTransaction(deletedRow());

    await deleteScopedResponse(RESPONSE_ID, SCOPE);

    // Not a correctness requirement — with a real workspace id an empty list is a harmless no-op — so
    // this pins the intent rather than a hazard: a response with no uploads must not reach storage at
    // all, which keeps the S3 client off the common path.
    expect(mockDeleteFiles).not.toHaveBeenCalled();
  });

  /**
   * A failed file cleanup must not report a failed delete: the row is already gone and the caller's
   * request succeeded. Orphaned objects are a storage problem, logged loudly. The audit row still comes
   * back — the delete happened, so the trail must record it even though cleanup did not finish.
   */
  test("still succeeds when storage cleanup fails, and still returns the audit row", async () => {
    runTransaction(deletedRow({ data: { screenshots: ["https://s/a.png"] } }));
    mockDeleteFiles.mockRejectedValue(new Error("storage down"));

    await expect(deleteScopedResponse(RESPONSE_ID, SCOPE)).resolves.toMatchObject({ id: RESPONSE_ID });
  });

  /**
   * A scoped delete matching nothing raises P2025, and that has to become the error the shared mapper
   * renders as the *same* 403 a pre-flight rejection produces — otherwise a foreign id is
   * distinguishable from a nonexistent one.
   */
  test("turns a P2025 into ResourceNotFoundError, before anything can wrap it", async () => {
    const { Prisma } = await import("@formbricks/database/prisma");
    const KnownRequestError = Prisma.PrismaClientKnownRequestError as unknown as new (
      message: string,
      code: string
    ) => Error;
    mockTransaction.mockRejectedValue(new KnownRequestError("no rows", "P2025"));

    await expect(deleteScopedResponse(RESPONSE_ID, SCOPE)).rejects.toBeInstanceOf(ResourceNotFoundError);
  });
});

describe("getResponseWorkspaceId", () => {
  beforeEach(() => vi.clearAllMocks());

  test("resolves the owning workspace through the survey", async () => {
    mockFindFirst.mockResolvedValue({ survey: { workspaceId: "ws_9" } });

    await expect(getResponseWorkspaceId(RESPONSE_ID)).resolves.toBe("ws_9");
  });

  test("answers null for an unknown response, leaving the 403 to the caller", async () => {
    mockFindFirst.mockResolvedValue(null);

    await expect(getResponseWorkspaceId(RESPONSE_ID)).resolves.toBeNull();
  });
});

/**
 * The batch path's own unit tests. Its behaviour against real SQL — scope-filtering, the authoritative
 * count, the FK-safe ordering — is proven in `service.integration.test.ts`, which is the only place it
 * can be. These cover the parts that are ours rather than Postgres's: what goes into each statement,
 * how the survey reads are grouped, and what comes back.
 */
describe("deleteScopedResponses", () => {
  const BATCH_IDS = ["clrsaaaaaaaaaaaaaaaaaaaa", "clrsbbbbbbbbbbbbbbbbbbbb"];

  /** A tx exposing the statements the batch issues, and the cleanup queue's two steps. */
  const runBatch = (
    rows: Record<string, unknown>[],
    { count = rows.length, surveys = [{ id: "svy_1", blocks: [], questions: [] }] } = {}
  ) => {
    mockTxFindMany.mockResolvedValue(rows);
    mockTxDeleteMany.mockResolvedValue({ count });
    mockTxSurveyMany.mockResolvedValue(surveys);
    mockTxDisplayDeleteMany.mockResolvedValue({ count: 0 });
    mockTxWorkspace.mockResolvedValue({ organizationId: "org_1" });
    mockEnqueue.mockResolvedValue({ drainNowIds: ["cln_1"] });
    mockDrain.mockResolvedValue({ done: 1, again: 0, failed: 0 });
    mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => fn(batchTx));
  };
  const batchTx = {
    response: { findMany: mockTxFindMany, deleteMany: mockTxDeleteMany },
    survey: { findMany: mockTxSurveyMany },
    display: { deleteMany: mockTxDisplayDeleteMany },
    workspace: { findUniqueOrThrow: mockTxWorkspace },
  };

  const row = (over: Record<string, unknown> = {}) => ({
    id: BATCH_IDS[0],
    displayId: null,
    data: {},
    surveyId: "svy_1",
    ...over,
  });

  beforeEach(() => vi.clearAllMocks());

  /**
   * The security core. Both statements must carry the scope: the read alone would let the delete take
   * ids the caller cannot see, and the delete alone would report a count for rows it never read.
   */
  test("scopes both the read and the delete by workspace", async () => {
    runBatch([row()]);

    await deleteScopedResponses(BATCH_IDS, SCOPE);

    expect(mockTxFindMany.mock.calls[0][0].where).toStrictEqual({
      id: { in: BATCH_IDS },
      survey: { workspaceId: "ws_1" },
    });
    // Still scoped, and narrowed to the rows read, so only rows whose files were collected are deleted.
    expect(mockTxDeleteMany.mock.calls[0][0].where).toStrictEqual({
      AND: [{ id: { in: BATCH_IDS }, survey: { workspaceId: "ws_1" } }, { id: { in: [row().id] } }],
    });
  });

  /**
   * `deleteMany` knows what it removed; the earlier read does not. A concurrent caller can take a row
   * in between, and reporting the read's length would then overstate the deletion.
   */
  test("reports the delete's own count, not the number of rows read", async () => {
    runBatch([row({ id: BATCH_IDS[0] }), row({ id: BATCH_IDS[1] })], { count: 1 });

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).resolves.toMatchObject({ deleted: 1 });
  });

  test("short-circuits without deleting or queueing anything when nothing is in scope", async () => {
    runBatch([]);

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).resolves.toStrictEqual({
      deleted: 0,
      deletedIds: [],
    });
    expect(mockTxDeleteMany).not.toHaveBeenCalled();
    expect(mockEnqueue).not.toHaveBeenCalled();
    expect(mockDrain).toHaveBeenCalledWith({ ids: [] });
  });

  /**
   * One read per distinct survey, not per response. At the 100-id cap the per-row form would be 100
   * queries to collect a handful of file-upload element ids.
   */
  test("reads each distinct survey once, however many responses reference it", async () => {
    runBatch([row({ surveyId: "svy_1" }), row({ surveyId: "svy_1" }), row({ surveyId: "svy_2" })], {
      surveys: [
        { id: "svy_1", blocks: [], questions: [] },
        { id: "svy_2", blocks: [], questions: [] },
      ],
    });

    await deleteScopedResponses(BATCH_IDS, SCOPE);

    expect(mockTxSurveyMany).toHaveBeenCalledTimes(1);
    expect(mockTxSurveyMany.mock.calls[0][0].where).toStrictEqual({ id: { in: ["svy_1", "svy_2"] } });
  });

  test("removes the linked displays, and skips the statement when there are none", async () => {
    runBatch([row({ displayId: "cldp_1" }), row({ displayId: null })]);

    await deleteScopedResponses(BATCH_IDS, SCOPE);

    expect(mockTxDisplayDeleteMany).toHaveBeenCalledWith({ where: { id: { in: ["cldp_1"] } } });

    vi.clearAllMocks();
    runBatch([row({ displayId: null })]);
    await deleteScopedResponses(BATCH_IDS, SCOPE);
    expect(mockTxDisplayDeleteMany).not.toHaveBeenCalled();
  });

  /**
   * Files and Hub records go through the cleanup queue, written in the delete's own transaction: a
   * delete that commits always gets its cleanup, retried until done. Only the files are drained at once.
   */
  test("queues each survey's files and Hub records in the delete's transaction, then drains the files", async () => {
    const order: string[] = [];
    runBatch(
      [
        row({ id: BATCH_IDS[0], surveyId: "svy_1", data: { screenshots: ["https://s/a.png"] } }),
        row({ id: BATCH_IDS[1], surveyId: "svy_2", data: { screenshots: ["https://s/b.png"] } }),
      ],
      {
        surveys: [
          { id: "svy_1", blocks: [], questions: [] },
          { id: "svy_2", blocks: [], questions: [] },
        ],
      }
    );
    mockEnqueue.mockImplementation(async () => {
      order.push("enqueue");
      return { drainNowIds: ["cln_1", "cln_2"] };
    });
    mockTransaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => {
      const out = await fn(batchTx);
      order.push("commit");
      return out;
    });
    mockDrain.mockImplementation(async () => void order.push("drain"));

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).resolves.toStrictEqual({
      deleted: 2,
      deletedIds: BATCH_IDS,
    });

    expect(order).toStrictEqual(["enqueue", "commit", "drain"]);
    expect(mockTxWorkspace).toHaveBeenCalledWith({ where: { id: "ws_1" }, select: { organizationId: true } });
    expect(mockEnqueue).toHaveBeenCalledWith(batchTx, {
      organizationId: "org_1",
      workspaceId: "ws_1",
      surveys: [
        { surveyId: "svy_1", responseIds: [BATCH_IDS[0]], fileUrls: ["https://s/a.png"] },
        { surveyId: "svy_2", responseIds: [BATCH_IDS[1]], fileUrls: ["https://s/b.png"] },
      ],
    });
    expect(mockDrain).toHaveBeenCalledWith({ ids: ["cln_1", "cln_2"] });
    // No storage call outside the queue any more.
    expect(mockDeleteFiles).not.toHaveBeenCalled();
  });

  // Each row is bound to its own survey: svy_1's removed-element upload goes, but the same key in a
  // svy_2 response is another survey's file and stays.
  test("queues removed-element uploads by each row's own survey id", async () => {
    const svy1File = "/storage/ws_1/private/surveys/svy_1/elements/removed/a.png";
    runBatch(
      [
        row({ id: BATCH_IDS[0], surveyId: "svy_1", data: { removed: [svy1File] } }),
        row({ id: BATCH_IDS[1], surveyId: "svy_2", data: { removed: [svy1File] } }),
      ],
      {
        surveys: [
          { id: "svy_1", blocks: [], questions: [] },
          { id: "svy_2", blocks: [], questions: [] },
        ],
      }
    );

    await deleteScopedResponses(BATCH_IDS, SCOPE);

    expect(mockEnqueue.mock.calls[0][1].surveys).toStrictEqual([
      { surveyId: "svy_1", responseIds: [BATCH_IDS[0]], fileUrls: [svy1File] },
      { surveyId: "svy_2", responseIds: [BATCH_IDS[1]], fileUrls: [] },
    ]);
  });

  test("still succeeds when draining the files fails: the queue keeps them for the drain job", async () => {
    runBatch([row({ data: { screenshots: ["https://s/a.png"] } })]);
    mockDrain.mockRejectedValue(new Error("storage down"));

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).resolves.toMatchObject({ deleted: 1 });
  });

  test("rolls back with nothing deleted when queueing the cleanup fails", async () => {
    runBatch([row()]);
    mockEnqueue.mockRejectedValue(new Error("insert failed"));

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).rejects.toThrow("insert failed");
    expect(mockDrain).not.toHaveBeenCalled();
  });

  /**
   * The catch must rethrow, not absorb. Swallowing here would surface as `deleted: 0` — a 200 telling
   * the caller nothing matched, when in fact the transaction failed and rows may still be there.
   */
  test("propagates a failed transaction instead of reporting nothing deleted", async () => {
    mockTransaction.mockRejectedValue(new Error("connection reset"));

    await expect(deleteScopedResponses(BATCH_IDS, SCOPE)).rejects.toThrow("connection reset");
  });

  /** Same decision as the single delete, and a batch would multiply the damage by up to 100. */
  test("never shrinks a configured quota limit", async () => {
    runBatch([row()]);

    await deleteScopedResponses(BATCH_IDS, SCOPE);

    expect(mockReduceQuotas).not.toHaveBeenCalled();
  });
});

/**
 * `Survey.blocks` is `Json[] @default([])` and `ZSurvey.blocks` uses `.prefault([])`, so a row with
 * empty `blocks` and populated `questions` is representable and schema-valid — the blocks migration
 * having run is not a guarantee one cannot be met. The answer plan is built from `blocks` alone, so
 * such a survey would report every stored answer as `elementNotInSurvey`: a live survey's answers
 * returned as orphans.
 */
describe("legacy surveys whose blocks were never backfilled", () => {
  const legacyQuestion = {
    id: "clq1aaaaaaaaaaaaaaaaaaaa",
    type: "openText",
    headline: { default: "How did it go?" },
    required: false,
    inputType: "text",
    charLimit: {},
  };

  const surveyRow = (over: Record<string, unknown>) => ({
    id: "clsv1111111111111111111a",
    name: "Legacy",
    workspaceId: "ws_1",
    updatedAt: new Date("2026-09-01T00:00:00.000Z"),
    blocks: [],
    questions: [],
    languages: [],
    embeddedDataLinks: [],
    ...over,
  });

  test("blocks are derived from questions when the column is empty", async () => {
    mockSurveyFindMany
      .mockResolvedValueOnce([surveyRow({})])
      .mockResolvedValueOnce([{ id: "clsv1111111111111111111a", questions: [legacyQuestion] }]);

    const surveys = await getV3ResponseSurveys(["clsv1111111111111111111a"]);
    const derived = surveys.get("clsv1111111111111111111a");

    expect(derived?.blocks.length).toBeGreaterThan(0);
    expect(JSON.stringify(derived?.blocks)).toContain(legacyQuestion.id);
  });

  /** A migrated survey must not be re-derived — the stored blocks are the source of truth. */
  /**
   * The rescue costs nothing on the common path: a page whose surveys all have blocks issues no
   * second query at all.
   */
  test("a survey that already has blocks is left alone, and costs no extra query", async () => {
    const blocks = [{ id: "blk", name: "B", elements: [] }];
    mockSurveyFindMany.mockResolvedValueOnce([surveyRow({ blocks })]);

    const surveys = await getV3ResponseSurveys(["clsv1111111111111111111a"]);

    expect(surveys.get("clsv1111111111111111111a")?.blocks).toEqual(blocks);
    expect(mockSurveyFindMany).toHaveBeenCalledTimes(1);
  });

  test("a survey with neither blocks nor questions stays empty rather than throwing", async () => {
    mockSurveyFindMany
      .mockResolvedValueOnce([surveyRow({})])
      .mockResolvedValueOnce([{ id: "clsv1111111111111111111a", questions: [] }]);

    const surveys = await getV3ResponseSurveys(["clsv1111111111111111111a"]);

    expect(surveys.get("clsv1111111111111111111a")?.blocks).toEqual([]);
  });
});
