import { describe, expect, test } from "vitest";
import * as xlsx from "xlsx";
import { Prisma } from "@formbricks/database/prisma";
import { embeddedFieldsFromLegacyInput } from "@formbricks/types/embedded-data-mapping";
import {
  type TEmbeddedValueResponse,
  type TLinkedEmbeddedField,
} from "@formbricks/types/embedded-data-resolver";
import { InvalidInputError } from "@formbricks/types/errors";
import { TResponse, TResponseFilterCriteria, ZResponseFilterCriteria } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { convertToCsv, convertToXlsxBuffer } from "@/lib/utils/file-conversion";
import {
  calculateTtcTotal,
  extractChoiceIdsFromResponse,
  extractSurveyDetails,
  getChoiceIdByValue,
  getReservedFilterEntries,
  getResponseContactAttributes,
  getResponseHiddenFields,
  getResponseMeta,
  getResponseReservedFilterValues,
  getResponseVariableFilterValues,
  getResponsesFileName,
  getResponsesJson,
} from "./utils";
import { RESERVED_FILTER_LOCATORS, buildWhereClause } from "./where-clause";

/**
 * A survey as a reader actually receives it: `transformPrismaSurvey` inlines the EmbeddedData rows
 * next to the legacy columns, and since ENG-2412 those rows are the only thing the accessors read.
 * Fixtures that declare `variables` / `hiddenFields` alone describe a row nobody reads.
 */
// Returns a full TSurvey because that is what every consumer below takes. Deliberately not
// generic: inferring the type parameter from those uses made TypeScript demand the whole survey
// shape from fixtures that are partial on purpose.
const asRead = (survey: Partial<TSurvey>): TSurvey =>
  ({ ...survey, embeddedFields: embeddedFieldsFromLegacyInput(survey) }) as unknown as TSurvey;

/** One stored ingested row whose display name need not match the key its value lives under. */
const ingestedRow = (name: string, storageKey: string): TLinkedEmbeddedField => ({
  field: { name, key: null, source: "ingested", dataType: "string", defaultValue: null, locked: false },
  link: { storageKey },
});

describe("Response Utils", () => {
  describe("calculateTtcTotal", () => {
    test("should calculate total time correctly", () => {
      const ttc = {
        question1: 10,
        question2: 20,
        question3: 30,
      };
      const result = calculateTtcTotal(ttc);
      expect(result._total).toBe(60);
    });

    test("should handle empty ttc object", () => {
      const ttc = {};
      const result = calculateTtcTotal(ttc);
      expect(result._total).toBe(0);
    });
  });

  describe("getChoiceIdByValue", () => {
    const element = {
      id: "q1",
      type: "multipleChoiceSingle",
      choices: [
        { id: "alpha", label: { default: "Alpha", de: "Alpha-DE" } },
        { id: "no", label: { default: "No", de: "Nein" } },
        { id: "other", label: { default: "Other", de: "Andere" } },
      ],
    } as unknown as Parameters<typeof getChoiceIdByValue>[1];

    test("matches the default label", () => {
      expect(getChoiceIdByValue("No", element)).toBe("no");
    });

    test("matches a translated label for the response language", () => {
      expect(getChoiceIdByValue("Alpha-DE", element, "de")).toBe("alpha");
    });

    test("prefers the response-language label over an earlier choice's default label", () => {
      const clash = {
        ...element,
        choices: [
          { id: "first", label: { default: "Nein", de: "Erste" } },
          { id: "second", label: { default: "Second", de: "Nein" } },
        ],
      } as Parameters<typeof getChoiceIdByValue>[1];
      expect(getChoiceIdByValue("Nein", clash, "de")).toBe("second");
    });

    test("falls back to the default label when the choice has no translation", () => {
      const untranslated = {
        ...element,
        choices: [{ id: "c", label: { default: "Maybe" } }],
      } as Parameters<typeof getChoiceIdByValue>[1];
      expect(getChoiceIdByValue("Maybe", untranslated, "de")).toBe("c");
    });

    test("does not match other languages' labels as free text", () => {
      expect(getChoiceIdByValue("Nein", element)).toBe("other");
    });

    test("falls back to other for free text", () => {
      expect(getChoiceIdByValue("something else", element, "de")).toBe("other");
    });
  });

  describe("buildWhereClause", () => {
    const mockSurvey: Partial<TSurvey> = asRead({
      id: "survey1",
      name: "Test Survey",
      blocks: [],
      questions: [],
      type: "app",
      hiddenFields: { enabled: true, fieldIds: [] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "env1",
      createdBy: "user1",
      status: "draft",
    });

    test("should build where clause with finished filter", () => {
      const filterCriteria = { finished: true };
      const result = buildWhereClause(mockSurvey as TSurvey, filterCriteria);
      expect(result.AND).toContainEqual({ finished: true });
    });

    test("should build where clause with the Low quality outcome filter", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, { outcome: "lowQuality" });
      expect(result.AND).toContainEqual({ outcome: "lowQuality" });
    });

    test("should not constrain the outcome unless asked to", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, { finished: true });
      expect(result.AND).not.toContainEqual(expect.objectContaining({ outcome: expect.anything() }));
    });

    test("should build where clause with date range", () => {
      const filterCriteria = {
        createdAt: {
          min: new Date("2024-01-01"),
          max: new Date("2024-12-31"),
        },
      };
      const result = buildWhereClause(mockSurvey as TSurvey, filterCriteria);
      expect(result.AND).toContainEqual({
        createdAt: {
          gte: new Date("2024-01-01"),
          lte: new Date("2024-12-31"),
        },
      });
    });

    test("should build where clause with tags", () => {
      const filterCriteria = {
        tags: {
          applied: ["tag1", "tag2"],
          notApplied: ["tag3"],
        },
      };
      const result = buildWhereClause(mockSurvey as TSurvey, filterCriteria);
      expect(result.AND).toHaveLength(1);
    });

    test("tagged with any of: one clause that matches either tag, beside the must-have ones", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, {
        tags: { applied: ["beta"], appliedAny: ["vip", "churn risk"] },
      });
      expect(result.AND).toEqual([
        {
          AND: [
            { tags: { some: { tag: { name: "beta" } } } },
            { tags: { some: { tag: { name: { in: ["vip", "churn risk"] } } } } },
          ],
        },
      ]);
    });

    test("should build where clause with contact attributes", () => {
      const filterCriteria = {
        contactAttributes: {
          email: { op: "equals" as const, value: "test@example.com" },
        },
      };
      const result = buildWhereClause(mockSurvey as TSurvey, filterCriteria);
      expect(result.AND).toHaveLength(1);
    });

    test("should build where clause with contact attribute exclusions", () => {
      const filterCriteria = {
        contactAttributes: {
          email: { op: "notEquals" as const, value: "blocked@example.com" },
        },
      };
      const result = buildWhereClause(mockSurvey as TSurvey, filterCriteria);
      expect(result.AND).toEqual([
        {
          AND: [{ contactAttributes: { path: ["email"], not: "blocked@example.com" } }],
        },
      ]);
    });

    test("should build where clause with response IDs", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, { responseIds: ["response1", "response2"] });
      expect(result.AND).toContainEqual({ id: { in: ["response1", "response2"] } });
    });

    test("should build where clause with quota filters", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, {
        quotas: {
          quota1: { op: "screenedOutNotInQuota" },
          quota2: { op: "screenedIn" },
        },
      });

      expect(result.AND).toContainEqual({
        AND: [
          {
            NOT: {
              quotaLinks: {
                some: {
                  quotaId: "quota1",
                },
              },
            },
          },
          {
            quotaLinks: {
              some: {
                quotaId: "quota2",
                status: "screenedIn",
              },
            },
          },
        ],
      });
    });

    test("should omit empty quota filters", () => {
      const result = buildWhereClause(mockSurvey as TSurvey, { quotas: {} });
      expect(result.AND).toEqual([]);
    });
  });

  describe("buildWhereClause – others & meta filters", () => {
    const baseSurvey: Partial<TSurvey> = {
      id: "s1",
      name: "Survey",
      blocks: [],
      questions: [],
      type: "app",
      hiddenFields: { enabled: false, fieldIds: [] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "e1",
      createdBy: "u1",
      status: "inProgress",
    };

    test("others: equals & notEquals", () => {
      const criteria = {
        others: {
          Language: { op: "equals" as const, value: "en" },
          Region: { op: "notEquals" as const, value: "APAC" },
        },
      };
      const result = buildWhereClause(baseSurvey as TSurvey, criteria);
      expect(result.AND).toEqual([
        {
          AND: [{ language: "en" }, { region: { not: "APAC" } }],
        },
      ]);
    });

    test("meta: equals & notEquals map to userAgent paths", () => {
      const criteria = {
        meta: {
          browser: { op: "equals" as const, value: "Chrome" },
          os: { op: "notEquals" as const, value: "Windows" },
        },
      };
      const result = buildWhereClause(baseSurvey as TSurvey, criteria);
      expect(result.AND).toEqual([
        {
          AND: [
            { meta: { path: ["userAgent", "browser"], equals: "Chrome" } },
            { meta: { path: ["userAgent", "os"], not: "Windows" } },
          ],
        },
      ]);
    });

    test("meta: URL string comparison operations", () => {
      const testCases = [
        {
          name: "contains",
          criteria: { meta: { url: { op: "contains" as const, value: "example.com" } } },
          expected: { meta: { path: ["url"], string_contains: "example.com" } },
        },
        {
          name: "doesNotContain",
          criteria: { meta: { url: { op: "doesNotContain" as const, value: "test.com" } } },
          expected: { NOT: { meta: { path: ["url"], string_contains: "test.com" } } },
        },
        {
          name: "startsWith",
          criteria: { meta: { url: { op: "startsWith" as const, value: "https://" } } },
          expected: { meta: { path: ["url"], string_starts_with: "https://" } },
        },
        {
          name: "doesNotStartWith",
          criteria: { meta: { url: { op: "doesNotStartWith" as const, value: "http://" } } },
          expected: { NOT: { meta: { path: ["url"], string_starts_with: "http://" } } },
        },
        {
          name: "endsWith",
          criteria: { meta: { url: { op: "endsWith" as const, value: ".com" } } },
          expected: { meta: { path: ["url"], string_ends_with: ".com" } },
        },
        {
          name: "doesNotEndWith",
          criteria: { meta: { url: { op: "doesNotEndWith" as const, value: ".org" } } },
          expected: { NOT: { meta: { path: ["url"], string_ends_with: ".org" } } },
        },
      ];

      testCases.forEach(({ criteria, expected }) => {
        const result = buildWhereClause(baseSurvey as TSurvey, criteria);
        expect(result.AND).toEqual([{ AND: [expected] }]);
      });
    });
  });

  describe("buildWhereClause – data‐field filter operations", () => {
    const textSurvey: Partial<TSurvey> = {
      id: "s2",
      name: "TextSurvey",
      blocks: [
        {
          id: "block1",
          name: "Block 1",
          elements: [
            {
              id: "qText",
              type: TSurveyElementTypeEnum.OpenText,
              headline: { default: "Text Q" },
              required: false,
              isDraft: false,
              charLimit: {},
              inputType: "text",
            },
            {
              id: "qNum",
              type: TSurveyElementTypeEnum.OpenText,
              headline: { default: "Num Q" },
              required: false,
              isDraft: false,
              charLimit: {},
              inputType: "number",
            },
          ],
        },
      ],
      questions: [],
      type: "app",
      hiddenFields: { enabled: false, fieldIds: [] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "e2",
      createdBy: "u2",
      status: "inProgress",
    };

    const ops: Array<[string, NonNullable<TResponseFilterCriteria["data"]>[string], unknown]> = [
      ["submitted", { op: "submitted" }, { path: ["qText"], not: Prisma.DbNull }],
      ["filledOut", { op: "filledOut" }, { path: ["qText"], not: [] }],
      ["skipped", { op: "skipped" }, "OR"],
      ["equals", { op: "equals", value: "foo" }, { path: ["qText"], equals: "foo" }],
      ["notEquals", { op: "notEquals", value: "bar" }, "NOT"],
      ["lessThan", { op: "lessThan", value: 5 }, { path: ["qNum"], lt: 5 }],
      ["lessEqual", { op: "lessEqual", value: 10 }, { path: ["qNum"], lte: 10 }],
      ["greaterThan", { op: "greaterThan", value: 1 }, { path: ["qNum"], gt: 1 }],
      ["greaterEqual", { op: "greaterEqual", value: 2 }, { path: ["qNum"], gte: 2 }],
      [
        "includesAll",
        { op: "includesAll", value: ["a", "b"] },
        { path: ["qText"], array_contains: ["a", "b"] },
      ],
    ];

    ops.forEach(([name, filter, expected]) => {
      test(name, () => {
        const result = buildWhereClause(textSurvey as TSurvey, {
          data: {
            [["submitted", "filledOut", "equals", "includesAll"].includes(name) ? "qText" : "qNum"]: filter,
          },
        });
        // for OR/NOT cases we just ensure the operator key exists
        if (expected === "OR" || expected === "NOT") {
          expect(JSON.stringify(result)).toMatch(
            new RegExp(
              name === "skipped" ? `"OR":\\s*\\[` : `"not":"${"value" in filter ? String(filter.value) : ""}"`
            )
          );
        } else {
          expect(result.AND).toEqual([
            {
              AND: [{ data: expected }],
            },
          ]);
        }
      });
    });

    test("uploaded & notUploaded", () => {
      const res1 = buildWhereClause(textSurvey as TSurvey, { data: { qText: { op: "uploaded" } } });
      expect(res1.AND).toContainEqual({
        AND: [{ data: { path: ["qText"], not: "skipped" } }],
      });

      const res2 = buildWhereClause(textSurvey as TSurvey, { data: { qText: { op: "notUploaded" } } });
      expect(JSON.stringify(res2)).toMatch(/"equals":"skipped"/);
      expect(JSON.stringify(res2)).toMatch(/"equals":{}/);
    });

    test("clicked, accepted & booked", () => {
      ["clicked", "accepted", "booked"].forEach((status) => {
        const key = status as "clicked" | "accepted" | "booked";
        const res = buildWhereClause(textSurvey as TSurvey, { data: { qText: { op: key } } });
        expect(res.AND).toEqual([{ AND: [{ data: { path: ["qText"], equals: status } }] }]);
      });
    });

    test("matrix", () => {
      const matrixSurvey: Partial<TSurvey> = {
        id: "s3",
        name: "MatrixSurvey",
        blocks: [
          {
            id: "block1",
            name: "Block 1",
            elements: [
              {
                id: "qM",
                type: TSurveyElementTypeEnum.Matrix,
                headline: { default: "Matrix" },
                required: false,
                rows: [{ id: "r1", label: { default: "R1" } }],
                columns: [{ id: "c1", label: { default: "C1" } }],
                shuffleOption: "none",
                isDraft: false,
              },
            ],
          },
        ],
        questions: [],
        type: "app",
        hiddenFields: { enabled: false, fieldIds: [] },
        createdAt: new Date(),
        updatedAt: new Date(),
        workspaceId: "e3",
        createdBy: "u3",
        status: "inProgress",
      };
      const res = buildWhereClause(matrixSurvey as TSurvey, {
        data: { qM: { op: "matrix", value: { R1: "foo" } } },
      });
      expect(res.AND).toEqual([
        {
          AND: [
            {
              data: { path: ["qM", "R1"], equals: "foo" },
            },
          ],
        },
      ]);
    });

    test("matrix rules on several rows all apply", () => {
      const res = buildWhereClause(
        {
          id: "s4",
          blocks: [],
          questions: [],
          hiddenFields: { enabled: false, fieldIds: [] },
        } as unknown as TSurvey,
        {
          data: { qM: { op: "matrix", value: { R1: "foo", R2: "bar" } } },
        }
      );
      expect(res.AND).toEqual([
        {
          AND: [
            { data: { path: ["qM", "R1"], equals: "foo" } },
            { data: { path: ["qM", "R2"], equals: "bar" } },
          ],
        },
      ]);
    });

    test("includesOne: multiple choice multi with other choice selected", () => {
      const choiceSurvey: Partial<TSurvey> = {
        id: "s4",
        name: "ChoiceSurvey",
        blocks: [
          {
            id: "block1",
            name: "Block 1",
            elements: [
              {
                id: "qMulti",
                type: TSurveyElementTypeEnum.MultipleChoiceMulti,
                headline: { default: "Pick many" },
                required: false,
                choices: [
                  { id: "a", label: { default: "A" } },
                  { id: "b", label: { default: "B" } },
                  { id: "other", label: { default: "Other" } },
                ],
                shuffleOption: "none",
                isDraft: false,
              },
            ],
          },
        ],
        questions: [],
        type: "app",
        hiddenFields: { enabled: false, fieldIds: [] },
        createdAt: new Date(),
        updatedAt: new Date(),
        workspaceId: "e4",
        createdBy: "u4",
        status: "inProgress",
      };

      const result = buildWhereClause(choiceSurvey as TSurvey, {
        data: { qMulti: { op: "includesOne", value: ["Other"] } },
      });

      // One probe per array position, each asserting the entry exists and is none of the predefined
      // labels. Exact toEqual, not arrayContaining: the old weak matcher is what let an unbounded
      // clause set pass as "correct" (ENG-3161).
      //
      // 11 positions, not 3: `choices.length` (a, b, other) plus OTHER_WRITE_IN_PROBE_SLACK. The
      // slack exists because a stored answer can be longer than the choice list — repeated entries,
      // or choices deleted after collection — and the write-in then sits past index 2.
      expect(result.AND).toEqual([
        {
          AND: [
            {
              OR: Array.from({ length: 11 }, (_unused, index) => ({
                AND: [
                  { data: { path: ["qMulti", String(index)], not: Prisma.DbNull } },
                  { data: { path: ["qMulti", String(index)], not: "A" } },
                  { data: { path: ["qMulti", String(index)], not: "B" } },
                ],
              })),
            },
          ],
        },
      ]);
    });

    test("includesOne: multiple choice single with other choice selected", () => {
      const choiceSurvey: Partial<TSurvey> = {
        id: "s5",
        name: "SingleChoiceSurvey",
        blocks: [
          {
            id: "block1",
            name: "Block 1",
            elements: [
              {
                id: "qSingle",
                type: TSurveyElementTypeEnum.MultipleChoiceSingle,
                headline: { default: "Pick one" },
                required: false,
                choices: [
                  { id: "a", label: { default: "A" } },
                  { id: "b", label: { default: "B" } },
                  { id: "other", label: { default: "Other" } },
                ],
                shuffleOption: "none",
                isDraft: false,
              },
            ],
          },
        ],
        questions: [],
        type: "app",
        hiddenFields: { enabled: false, fieldIds: [] },
        createdAt: new Date(),
        updatedAt: new Date(),
        workspaceId: "e5",
        createdBy: "u5",
        status: "inProgress",
      };

      const result = buildWhereClause(choiceSurvey as TSurvey, {
        data: { qSingle: { op: "includesOne", value: ["Other"] } },
      });

      expect(result.AND).toEqual([
        {
          AND: [
            {
              AND: [
                { NOT: { data: { path: ["qSingle"], equals: "A" } } },
                { NOT: { data: { path: ["qSingle"], equals: "B" } } },
              ],
            },
          ],
        },
      ]);
    });

    // Every record-shaped filter field is iterated per key by the builder, so the schema caps the
    // key count. These live here rather than in packages/types, which has no test runner.
    describe("filter record key caps (ENG-3161)", () => {
      // Each record field accepts its own condition shape, so the fixture varies per field.
      const CONDITION: Record<string, unknown> = {
        variables: { op: "isSet" },
        reserved: { op: "isSet" },
        meta: { op: "equals", value: "x" },
        contactAttributes: { op: "equals", value: "x" },
        data: { op: "submitted" },
        others: { op: "equals", value: "x" },
      };

      const withKeys = (field: string, count: number): unknown => ({
        [field]: Object.fromEntries(
          Array.from({ length: count }, (_unused, index) => [`k${index}`, CONDITION[field]])
        ),
      });

      // `variables` feeds buildVariableConditions, which emits a clause per recognised key. It was
      // the one record field missing from the refinement.
      test.each(Object.keys(CONDITION))("%s is capped at 500 keys", (field) => {
        expect(ZResponseFilterCriteria.safeParse(withKeys(field, 500)).success).toBe(true);
        expect(ZResponseFilterCriteria.safeParse(withKeys(field, 501)).success).toBe(false);
      });
    });

    test("dataAnd conditions apply alongside data on the same key", () => {
      const survey = {
        id: "s6",
        blocks: [],
        questions: [],
        hiddenFields: { enabled: false, fieldIds: [] },
      } as unknown as TSurvey;
      const result = buildWhereClause(survey, {
        data: { qRating: { op: "lessThan", value: 5 } },
        dataAnd: [{ key: "qRating", condition: { op: "greaterThan", value: 1 } }],
      });
      expect(result.AND).toEqual([
        {
          AND: [{ data: { path: ["qRating"], lt: 5 } }, { data: { path: ["qRating"], gt: 1 } }],
        },
      ]);
    });

    test("includesAll with Other needs the picked choices and a write-in", () => {
      const survey = {
        id: "s5",
        blocks: [
          {
            id: "b1",
            name: "Block 1",
            elements: [
              {
                id: "qMulti",
                type: TSurveyElementTypeEnum.MultipleChoiceMulti,
                headline: { default: "Pick many" },
                required: false,
                choices: [
                  { id: "a", label: { default: "A" } },
                  { id: "other", label: { default: "Other" } },
                ],
                shuffleOption: "none",
              },
            ],
          },
        ],
        questions: [],
        hiddenFields: { enabled: false, fieldIds: [] },
      } as unknown as TSurvey;

      const result = buildWhereClause(survey, {
        data: { qMulti: { op: "includesAll", value: ["A", "Other"] } },
      });

      expect(result.AND).toEqual([
        {
          AND: [
            { data: { path: ["qMulti"], array_contains: ["A"] } },
            {
              OR: Array.from({ length: 10 }, (_unused, index) => ({
                AND: [
                  { data: { path: ["qMulti", String(index)], not: Prisma.DbNull } },
                  { data: { path: ["qMulti", String(index)], not: "A" } },
                ],
              })),
            },
          ],
        },
      ]);
    });

    describe("includesOne: 'Other' clause budget (ENG-3161)", () => {
      /**
       * One choice element per id in `elementIds`, each carrying `choiceCount` predefined choices
       * (localized into every entry of `languages`) plus the "Other" choice.
       */
      const buildChoiceSurvey = (
        elementType: TSurveyElementTypeEnum.MultipleChoiceMulti | TSurveyElementTypeEnum.MultipleChoiceSingle,
        choiceCount: number,
        languages: string[] = ["default"],
        elementIds: string[] = ["q0"]
      ): TSurvey =>
        ({
          id: "sBudget",
          name: "BudgetSurvey",
          blocks: [
            {
              id: "block1",
              name: "Block 1",
              elements: elementIds.map((elementId) => ({
                id: elementId,
                type: elementType,
                headline: { default: "Pick" },
                required: false,
                choices: [
                  ...Array.from({ length: choiceCount }, (_unused, index) => ({
                    id: `c${index}`,
                    label: Object.fromEntries(
                      languages.map((language) => [language, `${language}-label-${index}`])
                    ),
                  })),
                  { id: "other", label: { default: "Other" } },
                ],
                shuffleOption: "none",
                isDraft: false,
              })),
            },
          ],
          questions: [],
          type: "app",
          hiddenFields: { enabled: false, fieldIds: [] },
          createdAt: new Date(),
          updatedAt: new Date(),
          workspaceId: "eBudget",
          createdBy: "uBudget",
          status: "inProgress",
        }) as unknown as TSurvey;

      const otherFilter = (elementIds: string[]): TResponseFilterCriteria => ({
        data: Object.fromEntries(
          elementIds.map((elementId) => [elementId, { op: "includesOne" as const, value: ["Other"] }])
        ),
      });

      // The multi branch probes (choices + 1 + SLACK) positions x (labels + 1) clauses, so a
      // monolingual element of c choices costs (c + 9)(c + 1): 9984 at c = 95, 10185 at c = 96.
      test("multi: a survey just inside the budget still builds", () => {
        const survey = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceMulti, 95);

        const result = buildWhereClause(survey, otherFilter(["q0"]));

        expect(result.AND).toHaveLength(1);
      });

      test("multi: a survey just past the budget is refused", () => {
        const survey = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceMulti, 96);

        expect(() => buildWhereClause(survey, otherFilter(["q0"]))).toThrow(InvalidInputError);
      });

      test("single: the label-count budget is enforced too", () => {
        const withinBudget = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceSingle, 10_000);
        expect(() => buildWhereClause(withinBudget, otherFilter(["q0"]))).not.toThrow();

        const pastBudget = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceSingle, 10_001);
        expect(() => buildWhereClause(pastBudget, otherFilter(["q0"]))).toThrow(InvalidInputError);
      });

      // The budget is per call, not per branch: filterCriteria.data is a record and every key is
      // expanded. This is the test that fails if the budget is ever made per-branch again.
      test("many individually-cheap filter keys still exhaust the budget", () => {
        const cheapIds = Array.from({ length: 5 }, (_unused, index) => `q${index}`);
        const cheapSurvey = buildChoiceSurvey(
          TSurveyElementTypeEnum.MultipleChoiceMulti,
          35,
          ["default"],
          cheapIds
        );
        // 5 x (44 x 36) = 7920, inside the budget.
        expect(() => buildWhereClause(cheapSurvey, otherFilter(cheapIds))).not.toThrow();

        const manyIds = Array.from({ length: 10 }, (_unused, index) => `q${index}`);
        const manySurvey = buildChoiceSurvey(
          TSurveyElementTypeEnum.MultipleChoiceMulti,
          35,
          ["default"],
          manyIds
        );
        // 10 x (44 x 36) = 15840, past the budget, though each key alone is far inside it.
        expect(() => buildWhereClause(manySurvey, otherFilter(manyIds))).toThrow(InvalidInputError);
      });

      // Tags are the other client-supplied list that expands one clause per entry — a relation
      // subquery each — so they are charged against the same budget rather than a separate cap.
      test("applied tags are charged against the budget too", () => {
        const survey = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceMulti, 2);
        const tags = (count: number): TResponseFilterCriteria => ({
          tags: { applied: Array.from({ length: count }, (_unused, index) => `tag-${index}`) },
        });

        expect(() => buildWhereClause(survey, tags(10_000))).not.toThrow();
        expect(() => buildWhereClause(survey, tags(10_001))).toThrow(InvalidInputError);
      });

      // Every language variant of every label is a separate clause, which is how a modest-looking
      // survey reached the old factorial blow-up at 11 labels.
      test("extra languages count against the budget", () => {
        const monolingual = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceMulti, 60);
        expect(() => buildWhereClause(monolingual, otherFilter(["q0"]))).not.toThrow();

        const trilingual = buildChoiceSurvey(TSurveyElementTypeEnum.MultipleChoiceMulti, 60, [
          "default",
          "de",
          "fr",
        ]);
        expect(() => buildWhereClause(trilingual, otherFilter(["q0"]))).toThrow(InvalidInputError);
      });
    });

    test("includesOne: regular choice match", () => {
      const result = buildWhereClause(textSurvey as TSurvey, {
        data: { qText: { op: "includesOne", value: ["A", "B"] } },
      });

      expect(result.AND).toEqual([
        {
          AND: [
            {
              OR: [
                {
                  OR: [
                    { data: { path: ["qText"], array_contains: ["A"] } },
                    { data: { path: ["qText"], equals: "A" } },
                  ],
                },
                {
                  OR: [
                    { data: { path: ["qText"], array_contains: ["B"] } },
                    { data: { path: ["qText"], equals: "B" } },
                  ],
                },
              ],
            },
          ],
        },
      ]);
    });
  });

  describe("buildWhereClause – reserved + variables filters (ENG-1848)", () => {
    const reservedSurvey = asRead({
      id: "s3",
      name: "ReservedSurvey",
      blocks: [],
      questions: [],
      type: "link",
      hiddenFields: { enabled: true, fieldIds: [] },
      variables: [{ id: "var_score", name: "score", type: "number" as const, value: 0 }],
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "e3",
      createdBy: "u3",
      status: "inProgress",
    });

    test("reserved string field filters its meta path with the catalog name", () => {
      const result = buildWhereClause(reservedSurvey, {
        reserved: { utmSource: { op: "equals", value: "newsletter" } },
      });
      expect(result.AND).toContainEqual({
        AND: [{ meta: { path: ["utmSource"], equals: "newsletter" } }],
      });
    });

    test("deviceType remaps to the stored userAgent.device path", () => {
      const result = buildWhereClause(reservedSurvey, {
        reserved: { deviceType: { op: "equals", value: "desktop" } },
      });
      expect(result.AND).toContainEqual({
        AND: [{ meta: { path: ["userAgent", "device"], equals: "desktop" } }],
      });
    });

    test("number-typed reserved field compares numerically", () => {
      const result = buildWhereClause(reservedSurvey, {
        reserved: { screenWidth: { op: "greaterThan", value: 1000 } },
      });
      expect(result.AND).toContainEqual({
        AND: [{ meta: { path: ["screenWidth"], gt: 1000 } }],
      });
    });

    test("negated text ops wrap in NOT, and notEquals also matches absent values", () => {
      const contains = buildWhereClause(reservedSurvey, {
        reserved: { pagePath: { op: "doesNotContain", value: "/checkout" } },
      });
      expect(contains.AND).toContainEqual({
        AND: [{ NOT: { meta: { path: ["pagePath"], string_contains: "/checkout" } } }],
      });

      const notEquals = buildWhereClause(reservedSurvey, {
        reserved: { country: { op: "notEquals", value: "DE" } },
      });
      // Prisma.DbNull stringifies to {}, hence the regex assertion (same trick as notUploaded above).
      expect(JSON.stringify(notEquals.AND)).toMatch(
        /"OR":\[\{"meta":\{"path":\["country"\],"not":"DE"\}\},\{"meta":\{"path":\["country"\],"equals":\{\}\}\}\]/
      );
    });

    test("isSet / isNotSet match presence via DbNull", () => {
      const isSet = buildWhereClause(reservedSurvey, { reserved: { utmSource: { op: "isSet" } } });
      expect(JSON.stringify(isSet.AND)).toMatch(/"meta":\{"path":\["utmSource"\],"not":\{\}\}/);

      const isNotSet = buildWhereClause(reservedSurvey, { reserved: { utmSource: { op: "isNotSet" } } });
      expect(JSON.stringify(isNotSet.AND)).toMatch(/"meta":\{"path":\["utmSource"\],"equals":\{\}\}/);
    });

    test("durationSeconds filters ttc._total milliseconds through Math.round windows", () => {
      const equals = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "equals", value: 13 } },
      });
      expect(equals.AND).toContainEqual({
        AND: [
          {
            AND: [{ ttc: { path: ["_total"], gte: 12500 } }, { ttc: { path: ["_total"], lt: 13500 } }],
          },
        ],
      });

      // rounded > 60 starts at 60500ms (60499 rounds DOWN to 60), rounded < 60 ends below 59500.
      const greaterThan = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "greaterThan", value: 60 } },
      });
      expect(greaterThan.AND).toContainEqual({ AND: [{ ttc: { path: ["_total"], gte: 60500 } }] });

      const lessThan = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "lessThan", value: 60 } },
      });
      expect(lessThan.AND).toContainEqual({ AND: [{ ttc: { path: ["_total"], lt: 59500 } }] });
    });

    test("fails closed: shadowed, unknown, and type-mismatched conditions emit nothing", () => {
      // `url` is declared as an ingested field here, so the reserved read must never be queried.
      const shadowingSurvey = asRead({
        ...reservedSurvey,
        hiddenFields: { enabled: true, fieldIds: ["url"] },
      });
      const shadowed = buildWhereClause(shadowingSurvey, {
        reserved: { url: { op: "equals", value: "https://x.test" } },
      });
      expect(shadowed.AND).toContainEqual({ AND: [] });

      const unknown = buildWhereClause(reservedSurvey, {
        reserved: { notInCatalog: { op: "equals", value: "x" } },
      });
      expect(unknown.AND).toContainEqual({ AND: [] });

      // A text op on the number-typed duration entry has no meaningful translation.
      const mismatched = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "contains", value: "6" } },
      });
      expect(mismatched.AND).toContainEqual({ AND: [] });

      // Same for a text op on a number-typed meta entry: no filter that its value can never match.
      const textOnNumber = buildWhereClause(reservedSurvey, {
        reserved: { screenWidth: { op: "contains", value: "1" } },
      });
      expect(textOnNumber.AND).toContainEqual({ AND: [] });
    });

    test("prototype-chain keys never resolve a locator", () => {
      // z.record keys are unrestricted, so a crafted criteria can carry these; a plain index lookup
      // would resolve them through Object.prototype and hand Prisma an undefined path.
      const crafted = JSON.parse(
        '{"__proto__":{"op":"equals","value":"x"},"constructor":{"op":"equals","value":"x"},"hasOwnProperty":{"op":"isSet"}}'
      );
      const result = buildWhereClause(reservedSurvey, { reserved: crafted });
      expect(result.AND).toContainEqual({ AND: [] });
    });

    test("every comparison and text-op arm translates one-to-one", () => {
      const cases: Array<[object, object]> = [
        [
          { screenWidth: { op: "lessThan" as const, value: 800 } },
          { meta: { path: ["screenWidth"], lt: 800 } },
        ],
        [
          { screenWidth: { op: "lessEqual" as const, value: 800 } },
          { meta: { path: ["screenWidth"], lte: 800 } },
        ],
        [
          { screenWidth: { op: "greaterEqual" as const, value: 800 } },
          { meta: { path: ["screenWidth"], gte: 800 } },
        ],
        [
          { pagePath: { op: "contains" as const, value: "/checkout" } },
          { meta: { path: ["pagePath"], string_contains: "/checkout" } },
        ],
        [
          { pagePath: { op: "startsWith" as const, value: "/app" } },
          { meta: { path: ["pagePath"], string_starts_with: "/app" } },
        ],
        [
          { pagePath: { op: "doesNotStartWith" as const, value: "/app" } },
          { NOT: { meta: { path: ["pagePath"], string_starts_with: "/app" } } },
        ],
        [
          { pagePath: { op: "endsWith" as const, value: "/done" } },
          { meta: { path: ["pagePath"], string_ends_with: "/done" } },
        ],
        [
          { pagePath: { op: "doesNotEndWith" as const, value: "/done" } },
          { NOT: { meta: { path: ["pagePath"], string_ends_with: "/done" } } },
        ],
      ];
      for (const [reserved, expected] of cases) {
        const result = buildWhereClause(reservedSurvey, { reserved } as never);
        expect(result.AND).toContainEqual({ AND: [expected] });
      }
    });

    test("duration bounds stay consistent with the projection at every boundary", () => {
      const lessEqual = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "lessEqual", value: 60 } },
      });
      expect(lessEqual.AND).toContainEqual({ AND: [{ ttc: { path: ["_total"], lt: 60500 } }] });

      const greaterEqual = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "greaterEqual", value: 60 } },
      });
      expect(greaterEqual.AND).toContainEqual({ AND: [{ ttc: { path: ["_total"], gte: 59500 } }] });

      const notEquals = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "notEquals", value: 13 } },
      });
      expect(JSON.stringify(notEquals.AND)).toMatch(
        /"OR":\[\{"ttc":\{"path":\["_total"\],"lt":12500\}\},\{"ttc":\{"path":\["_total"\],"gte":13500\}\},\{"ttc":\{"path":\["_total"\],"equals":\{\}\}\}\]/
      );

      // A non-numeric value cannot form a window — nothing is emitted.
      const notANumber = buildWhereClause(reservedSurvey, {
        reserved: { durationSeconds: { op: "equals", value: "abc" } },
      });
      expect(notANumber.AND).toContainEqual({ AND: [] });
    });

    test("data text ops: remaining arms translate one-to-one", () => {
      const cases: Array<[object, object]> = [
        [
          { plan: { op: "doesNotContain" as const, value: "trial" } },
          { NOT: { data: { path: ["plan"], string_contains: "trial" } } },
        ],
        [
          { plan: { op: "startsWith" as const, value: "gold" } },
          { data: { path: ["plan"], string_starts_with: "gold" } },
        ],
        [
          { plan: { op: "doesNotStartWith" as const, value: "gold" } },
          { NOT: { data: { path: ["plan"], string_starts_with: "gold" } } },
        ],
        [
          { plan: { op: "endsWith" as const, value: "-v2" } },
          { data: { path: ["plan"], string_ends_with: "-v2" } },
        ],
      ];
      for (const [data, expected] of cases) {
        const result = buildWhereClause(reservedSurvey, { data } as never);
        expect(result.AND).toContainEqual({ AND: [expected] });
      }
    });

    test("variables filter by computed storageKey, unknown keys emit nothing", () => {
      const known = buildWhereClause(reservedSurvey, {
        variables: { var_score: { op: "greaterEqual", value: 5 } },
      });
      expect(known.AND).toContainEqual({
        AND: [{ variables: { path: ["var_score"], gte: 5 } }],
      });

      const unknown = buildWhereClause(reservedSurvey, {
        variables: { not_a_variable: { op: "equals", value: 5 } },
      });
      expect(unknown.AND).toContainEqual({ AND: [] });
    });

    test("ingested string fields get text ops through the data group", () => {
      const result = buildWhereClause(reservedSurvey, {
        data: { plan: { op: "contains", value: "gold" } },
      });
      expect(result.AND).toContainEqual({
        AND: [{ data: { path: ["plan"], string_contains: "gold" } }],
      });

      const negated = buildWhereClause(reservedSurvey, {
        data: { plan: { op: "doesNotEndWith", value: "-trial" } },
      });
      expect(negated.AND).toContainEqual({
        AND: [{ NOT: { data: { path: ["plan"], string_ends_with: "-trial" } } }],
      });
    });

    test("anti-drift: every filterable catalog entry has a storage locator", () => {
      // The most permissive survey (nothing shadowed, nothing anonymized, IP captured) offers the
      // full filterable set — derived from the real function, so the rule lives in one place.
      const permissiveSurvey = {
        ...reservedSurvey,
        hiddenFields: { enabled: true, fieldIds: [] },
        variables: [],
        embeddedFields: [],
        isAnonymizeResponsesEnabled: false,
        isCaptureIpEnabled: true,
      } as TSurvey;
      const filterableNames = getReservedFilterEntries(permissiveSurvey).map((entry) => entry.name);
      expect(filterableNames.length).toBeGreaterThan(20);
      for (const name of filterableNames) {
        expect(RESERVED_FILTER_LOCATORS[name], `catalog entry "${name}" has no filter locator`).toBeDefined();
      }
    });
  });

  describe("getReservedFilterEntries (ENG-1848)", () => {
    const baseSurvey = asRead({
      id: "s4",
      name: "FilterEntriesSurvey",
      blocks: [],
      questions: [],
      type: "link",
      hiddenFields: { enabled: true, fieldIds: [] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "e4",
      createdBy: "u4",
      status: "inProgress",
      isAnonymizeResponsesEnabled: false,
      isCaptureIpEnabled: true,
    });

    test("offers the table's display entries plus durationSeconds, never ids or startedAt", () => {
      const names = getReservedFilterEntries(baseSurvey).map((entry) => entry.name);
      expect(names).toContain("utmSource");
      expect(names).toContain("browser");
      expect(names).toContain("durationSeconds");
      for (const excluded of ["responseId", "surveyId", "finished", "startedAt", "finishedAt", "language"]) {
        expect(names).not.toContain(excluded);
      }
    });

    test("a declared field owns its name — the reserved entry is dropped", () => {
      const shadowingSurvey = asRead({
        ...baseSurvey,
        hiddenFields: { enabled: true, fieldIds: ["url"] },
      });
      const names = getReservedFilterEntries(shadowingSurvey).map((entry) => entry.name);
      expect(names).not.toContain("url");
      expect(names).toContain("pagePath");
    });

    test("anonymized surveys keep hiding never-captured fields from the picker; ipAddress follows its capture toggle", () => {
      // ENG-2892 lifted the anonymize gate from the export only: the picker is about what the survey
      // collects from now on, the reserved export columns about what its responses hold.
      const anonymized = getReservedFilterEntries({
        ...baseSurvey,
        isAnonymizeResponsesEnabled: true,
      }).map((entry) => entry.name);
      for (const dropped of ["country", "browser", "os", "deviceType", "ipAddress"]) {
        expect(anonymized).not.toContain(dropped);
      }
      expect(anonymized).toContain("utmSource");

      const ipOff = getReservedFilterEntries({
        ...baseSurvey,
        isCaptureIpEnabled: false,
      }).map((entry) => entry.name);
      expect(ipOff).not.toContain("ipAddress");
      expect(ipOff).toContain("country");
    });
  });

  describe("filter value helpers (ENG-1848)", () => {
    const valueSurvey = asRead({
      id: "s5",
      name: "FilterValuesSurvey",
      blocks: [],
      questions: [],
      type: "link",
      hiddenFields: { enabled: true, fieldIds: [] },
      variables: [
        { id: "var_plan", name: "plan_name", type: "text" as const, value: "" },
        { id: "var_score", name: "score", type: "number" as const, value: 0 },
      ],
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "e5",
      createdBy: "u5",
      status: "inProgress",
    });

    const mkResponse = (over: Record<string, unknown>): TEmbeddedValueResponse => ({
      id: "r1",
      surveyId: "s5",
      createdAt: new Date(),
      updatedAt: new Date(),
      finished: true,
      language: null,
      data: {},
      variables: {},
      ttc: {},
      meta: {},
      ...over,
    });

    test("reserved values: distinct strings by catalog name, projected (url query-stripped), numbers skipped", () => {
      const values = getResponseReservedFilterValues(valueSurvey, [
        mkResponse({ meta: { utmSource: "newsletter", url: "https://x.test/p?email=leak@x.test" } }),
        mkResponse({ meta: { utmSource: "newsletter", screenWidth: 1280 } }),
        mkResponse({ meta: { utmSource: "ads" } }),
      ]);

      expect(values.utmSource).toEqual(["newsletter", "ads"]);
      // The dropdown gets the projected value, so the query string never leaks into filter options.
      expect(values.url).toEqual(["https://x.test/p"]);
      // Number-typed entries get a numeric input, not an options list.
      expect(values.screenWidth).toBeUndefined();
    });

    test("reserved values respect the per-survey gates", () => {
      const anonymized = { ...valueSurvey, isAnonymizeResponsesEnabled: true } as TSurvey;
      const values = getResponseReservedFilterValues(anonymized, [
        mkResponse({ meta: { country: "DE", utmSource: "ads" } }),
      ]);
      expect(values.country).toBeUndefined();
      expect(values.utmSource).toEqual(["ads"]);
    });

    test("high-cardinality fields are capped instead of shipping every distinct value", () => {
      const responses = Array.from({ length: 60 }, (_, i) =>
        mkResponse({ meta: { pagePath: `/product/${i}` } })
      );
      const values = getResponseReservedFilterValues(valueSurvey, responses);
      expect(values.pagePath).toHaveLength(50);
    });

    test("variable values: distinct strings keyed by storageKey, non-string fields and empties skipped", () => {
      const values = getResponseVariableFilterValues(valueSurvey, [
        mkResponse({ variables: { var_plan: "gold", var_score: 5 } }),
        mkResponse({ variables: { var_plan: "gold" } }),
        mkResponse({ variables: { var_plan: "" } }),
        mkResponse({ variables: { var_plan: "silver" } }),
      ]);

      expect(values.var_plan).toEqual(["gold", "silver"]);
      expect(values.var_score).toBeUndefined();
    });
  });

  describe("getResponsesFileName", () => {
    test("should generate correct filename", () => {
      const surveyName = "Test Survey";
      const extension = "csv";
      const result = getResponsesFileName(surveyName, extension);
      expect(result).toContain("export-test_survey-");
    });
  });

  // TODO: Fix this test after the survey editor poc is merged
  describe("extractSurveyDetails", () => {
    const mockSurvey: Partial<TSurvey> = asRead({
      id: "survey1",
      name: "Test Survey",
      blocks: [
        {
          id: "block1",
          name: "Block 1",
          elements: [
            {
              id: "q1",
              type: TSurveyElementTypeEnum.MultipleChoiceSingle,
              headline: { default: "Question 1" },
              required: true,
              choices: [
                { id: "1", label: { default: "Option 1" } },
                { id: "2", label: { default: "Option 2" } },
              ],
              shuffleOption: "none",
              isDraft: false,
            },
            {
              id: "q2",
              type: TSurveyElementTypeEnum.Matrix,
              headline: { default: "Matrix Question" },
              required: true,
              rows: [
                { id: "r1", label: { default: "Row 1" } },
                { id: "r2", label: { default: "Row 2" } },
              ],
              columns: [
                { id: "c1", label: { default: "Column 1" } },
                { id: "c2", label: { default: "Column 2" } },
              ],
              shuffleOption: "none",
              isDraft: false,
            },
          ],
        },
      ],
      questions: [],
      type: "app",
      hiddenFields: { enabled: true, fieldIds: ["hidden1"] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "env1",
      createdBy: "user1",
      status: "draft",
    });

    const mockResponses: Partial<TResponse>[] = [
      {
        id: "response1",
        surveyId: "survey1",
        data: {},
        meta: { userAgent: { browser: "Chrome" } },
        contactAttributes: { email: "test@example.com" },
        finished: true,
        createdAt: new Date(),
        updatedAt: new Date(),
        tags: [],
      },
    ];

    test("should extract survey details correctly", () => {
      const result = extractSurveyDetails(mockSurvey as TSurvey, mockResponses as TResponse[]);
      // Catalog-derived, not first-response-derived: the header exists whatever any response holds.
      expect(result.metaDataFields).toContain("Browser");
      expect(result.metaDataFields).toContain("Utm Source");
      expect(result.metaDataFields).not.toContain("userAgent - browser");
      expect(result.elements).toHaveLength(2); // 1 regular question + 2 matrix rows
      expect(result.hiddenFields).toContain("hidden1");
      expect(result.userAttributes).toContain("email");
    });

    // ENG-1847: the reserved column set is catalog-derived and stable — the four decisions below
    // (stability, shadowing, anonymize, basics dedupe) are each a rule reused from elsewhere, pinned
    // here so the export cannot drift from the response table.
    describe("reserved export columns (ENG-1847)", () => {
      test("columns are stable: a first response with NO meta still yields every catalog header", () => {
        // The old derivation read the FIRST response's meta keys, so this exact input produced zero
        // meta columns — red under that implementation.
        const bareResponse = { ...mockResponses[0], meta: {} } as TResponse;
        const result = extractSurveyDetails(mockSurvey as TSurvey, [bareResponse]);

        expect(result.metaDataFields).toContain("Utm Source");
        expect(result.metaDataFields).toContain("Page Path");
        expect(result.metaDataFields).toContain("Locale");
      });

      test("a survey declaring `url` does not get the reserved Url column — declared owns the name", () => {
        const shadowedSurvey = asRead({
          ...mockSurvey,
          hiddenFields: { enabled: true, fieldIds: ["url", "hidden1"] },
        });

        const result = extractSurveyDetails(shadowedSurvey, mockResponses as TResponse[]);

        expect(result.metaDataFields).not.toContain("Url");
        expect(result.hiddenFields).toContain("url");
      });

      test("an anonymized survey keeps the privacy-drop columns; Ip Address still follows its capture toggle", () => {
        // ENG-2892. Anonymize acts at ingest, so responses collected before the toggle still hold
        // country/browser/os/deviceType and the response table keeps showing them — only the export
        // hid them. Red on main, where `Country` was omitted.
        const anonymizedSurvey = {
          ...(mockSurvey as TSurvey),
          isAnonymizeResponsesEnabled: true,
          isCaptureIpEnabled: false,
        } as TSurvey;

        const result = extractSurveyDetails(anonymizedSurvey, mockResponses as TResponse[]);

        for (const kept of ["Country", "Browser", "Os", "Device Type", "Utm Source"]) {
          expect(result.metaDataFields).toContain(kept);
        }
        expect(result.metaDataFields).not.toContain("Ip Address");
      });

      test("facts the fixed basic columns already carry never become reserved columns", () => {
        const result = extractSurveyDetails(mockSurvey as TSurvey, mockResponses as TResponse[]);

        for (const doubled of ["Response Id", "Survey Id", "Finished", "Started At"]) {
          expect(result.metaDataFields).not.toContain(doubled);
        }
        // finishedAt/durationSeconds are NOT basics-covered — they must be columns.
        expect(result.metaDataFields).toContain("Finished At");
        expect(result.metaDataFields).toContain("Duration Seconds");
      });

      test("ipAddress is a column only when the survey captures it", () => {
        const withIp = { ...(mockSurvey as TSurvey), isCaptureIpEnabled: true } as TSurvey;
        const withoutIp = { ...(mockSurvey as TSurvey), isCaptureIpEnabled: false } as TSurvey;

        expect(extractSurveyDetails(withIp, mockResponses as TResponse[]).metaDataFields).toContain(
          "Ip Address"
        );
        expect(extractSurveyDetails(withoutIp, mockResponses as TResponse[]).metaDataFields).not.toContain(
          "Ip Address"
        );
      });
    });

    test("should collect contact attributes for link surveys too", () => {
      const linkSurvey = { ...mockSurvey, type: "link" } as TSurvey;
      const result = extractSurveyDetails(linkSurvey, mockResponses as TResponse[]);
      expect(result.userAttributes).toEqual(["email"]);
    });

    /**
     * ENG-1837: the export columns are built from the survey's Embedded Data definitions rather than
     * `variables` / `hiddenFields`. Both the grouping (both groups labelled by name since ENG-3233)
     * and the order inside each group are user-visible CSV/XLSX header order, so they are asserted
     * exactly, not by membership.
     */
    describe("Embedded Data columns", () => {
      // Legacy columns populated, join absent — `embeddedFields` is cleared explicitly because
      // `mockSurvey` carries the inlined rows a real read would have.
      const legacySurvey = {
        ...mockSurvey,
        variables: [
          { id: "clx0000000000000000000v2", name: "tier", type: "text", value: "" },
          { id: "clx0000000000000000000v1", name: "score", type: "number", value: 0 },
        ],
        hiddenFields: { enabled: true, fieldIds: ["utm_source", "hidden1"] },
        embeddedFields: undefined,
      } as unknown as TSurvey;

      test("reports no Embedded Data columns when the join is absent", () => {
        // ENG-2412 removed the legacy fallback, so the rows are the whole answer. A survey read
        // through a select that omits `selectSurveyEmbeddedDataLinks` exports no variable or hidden
        // field columns at all — which is why every reader's select has to carry that join.
        const result = extractSurveyDetails(legacySurvey, mockResponses as TResponse[]);

        expect(result.variables).toEqual([]);
        expect(result.hiddenFields).toEqual([]);
      });

      test("takes the column labels from the rows when the join is present", () => {
        const withRows = {
          ...legacySurvey,
          embeddedFields: [
            {
              field: {
                name: "renamed_tier",
                source: "computed",
                dataType: "string",
                defaultValue: "",
                locked: false,
              },
              link: { storageKey: "clx0000000000000000000v2" },
            },
            {
              field: {
                name: "score",
                source: "computed",
                dataType: "number",
                defaultValue: 0,
                locked: false,
              },
              link: { storageKey: "clx0000000000000000000v1" },
            },
            {
              field: {
                name: "utm_source",
                source: "ingested",
                dataType: "string",
                defaultValue: null,
                locked: false,
              },
              link: { storageKey: "utm_source" },
            },
          ],
        } as TSurvey;

        const result = extractSurveyDetails(withRows, mockResponses as TResponse[]);

        expect(result.variables).toEqual(["renamed_tier", "score"]);
        expect(result.hiddenFields).toEqual(["utm_source"]);
      });

      /**
       * ENG-3233. A shared library field's name differs from the key its value is stored under, and
       * so does any renamed local one; the header is the name either way. Red on main, which
       * exported `utm_campaign`.
       */
      test("an ingested column is headed by the field's name, not its storage key", () => {
        const renamed = {
          ...legacySurvey,
          embeddedFields: [ingestedRow("Campaign", "utm_campaign")],
        } as TSurvey;

        expect(extractSurveyDetails(renamed, mockResponses as TResponse[]).hiddenFields).toEqual([
          "Campaign",
        ]);
      });

      test("two ingested fields sharing a name keep distinct headers", () => {
        // Names carry no uniqueness constraint, and the rows below are keyed by header — two equal
        // headers would drop a column's values into the other's.
        const colliding = {
          ...legacySurvey,
          embeddedFields: [ingestedRow("Channel", "utm_channel"), ingestedRow("Channel", "partner_ref")],
        } as TSurvey;

        expect(extractSurveyDetails(colliding, mockResponses as TResponse[]).hiddenFields).toEqual([
          "Channel",
          "Channel (partner_ref)",
        ]);
      });

      /**
       * The other half of the same rule, and the one a name-only allocation misses: the row object
       * is keyed by header across the *whole* schema, not just this group, so a display name equal
       * to a column the export already writes would overwrite that column rather than add one. A
       * storage key never could — it is a safe identifier — but a library field's name is free text.
       */
      test.each([
        ["a fixed column", "Response ID", "resp_id", "Response ID (resp_id)"],
        // `formatFieldNameToTitleCase` heads the reserved `source` entry exactly this way.
        ["a reserved column", "Source", "utm_source", "Source (utm_source)"],
      ])("an ingested field named like %s does not take it", (_case, name, storageKey, expected) => {
        const shadowing = {
          ...legacySurvey,
          embeddedFields: [ingestedRow(name, storageKey)],
        } as TSurvey;

        expect(extractSurveyDetails(shadowing, mockResponses as TResponse[]).hiddenFields).toEqual([
          expected,
        ]);
      });
    });
  });

  describe("getResponsesJson", () => {
    const mockSurvey: Partial<TSurvey> = asRead({
      id: "survey1",
      name: "Test Survey",
      blocks: [
        {
          id: "block1",
          name: "Block 1",
          elements: [
            {
              id: "q1",
              type: TSurveyElementTypeEnum.MultipleChoiceSingle,
              headline: { default: "Question 1" },
              required: true,
              choices: [
                { id: "1", label: { default: "Option 1" } },
                { id: "2", label: { default: "Option 2" } },
              ],
              shuffleOption: "none",
              isDraft: false,
            },
          ],
        },
      ],
      questions: [],
      type: "app",
      hiddenFields: { enabled: true, fieldIds: [] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "env1",
      createdBy: "user1",
      status: "draft",
    });

    const mockResponses: Partial<TResponse>[] = [
      {
        id: "response1",
        surveyId: "survey1",
        data: { q1: "answer1" },
        meta: { userAgent: { browser: "Chrome" } },
        contactAttributes: { email: "test@example.com" },
        finished: true,
        createdAt: new Date(),
        updatedAt: new Date(),
        tags: [],
      },
    ];

    test("should generate correct JSON data", () => {
      const questionsHeadlines = [["1. Question 1"]];
      const userAttributes = ["email"];
      const result = getResponsesJson(
        mockSurvey as TSurvey,
        mockResponses as TResponse[],
        questionsHeadlines,
        userAttributes,
        false
      );
      expect(result[0]["Response ID"]).toBe("response1");
      expect(result[0]["Browser"]).toBe("Chrome");
      expect(result[0]["1. Question 1"]).toBe("answer1");
      expect(result[0]["person.email"]).toBe("test@example.com");
    });

    describe("matrix rows in two languages (ENG-6779)", () => {
      const matrixSurvey = asRead({
        id: "survey1",
        languages: [
          { default: true, enabled: true, language: { code: "en" } },
          { default: false, enabled: true, language: { code: "ar" } },
        ],
        blocks: [
          {
            id: "block1",
            name: "Block 1",
            elements: [
              {
                id: "qm",
                type: TSurveyElementTypeEnum.Matrix,
                headline: { default: "Rate us" },
                required: false,
                rows: [
                  { id: "r1", label: { default: "Speed", ar: "السرعة" } },
                  { id: "r2", label: { default: "Quality", ar: "الجودة" } },
                ],
                columns: [{ id: "c1", label: { default: "Good", ar: "جيد" } }],
              },
            ],
          },
        ],
        hiddenFields: { enabled: false, fieldIds: [] },
      } as unknown as Partial<TSurvey>);
      const headlines = [["1. Rate us - Speed", "1. Rate us - Quality"]];
      const exportRow = (language: string | null, data: Record<string, string>) =>
        getResponsesJson(
          matrixSurvey,
          [
            {
              id: "r",
              surveyId: "survey1",
              data: { qm: data },
              language,
              meta: {},
              contactAttributes: {},
              variables: {},
              finished: true,
              createdAt: new Date(),
              updatedAt: new Date(),
              tags: [],
            } as unknown as TResponse,
          ],
          headlines,
          []
        )[0];

      test("reads rows by the default label for a default-language response", () => {
        const row = exportRow("default", { Speed: "Good", Quality: "Good" });
        expect(row["1. Rate us - Speed"]).toBe("Good");
        expect(row["1. Rate us - Quality"]).toBe("Good");
      });

      test("reads rows by the respondent-language label for an Arabic response", () => {
        const row = exportRow("ar", { السرعة: "جيد", الجودة: "جيد" });
        expect(row["1. Rate us - Speed"]).toBe("جيد");
        expect(row["1. Rate us - Quality"]).toBe("جيد");
      });

      test("still reads default-label keys for a response in another language", () => {
        const row = exportRow("ar", { Speed: "Good" });
        expect(row["1. Rate us - Speed"]).toBe("Good");
        expect(row["1. Rate us - Quality"]).toBe("");
      });
    });

    test("a calculated true/false field is written true / false (ENG-6973)", () => {
      const booleanSurvey = {
        ...mockSurvey,
        blocks: [],
        embeddedFields: [
          {
            field: {
              key: null,
              name: "qualified",
              source: "computed",
              dataType: "boolean",
              defaultValue: null,
              locked: false,
            },
            link: { storageKey: "v_qualified" },
          },
        ],
      } as unknown as TSurvey;
      const exportOf = (value: boolean) =>
        getResponsesJson(
          booleanSurvey,
          [{ ...mockResponses[0], variables: { v_qualified: value } } as TResponse],
          [],
          [],
          false
        )[0];

      expect(exportOf(true)["qualified"]).toBe("true");
      expect(exportOf(false)["qualified"]).toBe("false");
    });

    test("a computed field named `__proto__` keeps its value, and reaches both writers", async () => {
      // `ZEmbeddedDataName` is a non-blank string, so `__proto__` is a legal variable name. On an
      // ordinary row object, assigning that key runs Object.prototype's inherited setter instead of
      // creating an own property, and the cell is silently lost. Asserted through the writers too,
      // because that is where the loss shows: `{}` in CSV, no cell in XLSX.
      //
      // Question headlines cannot reach this — they are exported as "1. <headline>" — and neither can
      // `person.<attribute>` or the reserved catalog. A display name used verbatim as a key is the
      // whole exposure.
      const protoSurvey = asRead({
        ...mockSurvey,
        blocks: [],
        variables: [{ id: "v1", name: "__proto__", type: "text", value: "" }],
      });
      const protoResponse = { ...mockResponses[0], variables: { v1: "kept" } } as TResponse;

      const result = getResponsesJson(protoSurvey, [protoResponse], [], [], false);

      expect(Object.keys(result[0])).toContain("__proto__");
      expect(result[0]["__proto__"]).toBe("kept");

      const headers = ["Response ID", "__proto__"];
      const csv = await convertToCsv(headers, result);
      expect(csv).toContain("kept");
      expect(csv).not.toContain("{}");

      // Read the cell rather than `sheet_to_json`, whose rows are ordinary objects and so cannot hold
      // a `__proto__` key either — that would test the assertion helper, not the writer.
      const sheet = xlsx.read(convertToXlsxBuffer(headers, result), { type: "buffer" });
      const cells = sheet.Sheets[sheet.SheetNames[0]];
      expect(cells.B1.v).toBe("__proto__");
      expect(cells.B2.v).toBe("kept");
    });

    test("reserved values are typed and projected: duration numeric, finishedAt ISO, url query redacted, absent empty", () => {
      const finishedAtDate = new Date("2026-08-30T10:00:00.000Z");
      const richResponse = {
        ...mockResponses[0],
        updatedAt: finishedAtDate,
        ttc: { _total: 12500 },
        meta: {
          ...mockResponses[0].meta,
          url: "https://example.com/pricing?email=leak@example.com",
        },
      } as unknown as TResponse;

      const result = getResponsesJson(
        mockSurvey as TSurvey,
        [richResponse] as TResponse[],
        [["1. Question 1"]],
        [],
        false
      );

      // number cell, seconds not milliseconds — real numeric in XLSX, not text
      expect(result[0]["Duration Seconds"]).toBe(13);
      expect(result[0]["Finished At"]).toBe("2026-08-30T10:00:00.000Z");
      // redactQuery is honoured on the export projection like every other projection
      expect(result[0]["Url"]).toBe("https://example.com/pricing");
      expect(String(result[0]["Url"])).not.toContain("leak@example.com");
      // a column whose value this response never captured is an empty cell, not a missing key
      expect(result[0]["Utm Source"]).toBe("");
    });

    test("an anonymized survey exports the privacy-drop columns: older values kept, anonymized rows empty", () => {
      // ENG-2892: the toggle acts at ingest, so a response collected before it still holds its country
      // while one captured afterwards never did. Both rows get the cell; only its content differs.
      const anonymizedSurvey = { ...(mockSurvey as TSurvey), isAnonymizeResponsesEnabled: true } as TSurvey;
      const olderResponse = {
        ...mockResponses[0],
        meta: { country: "DE", userAgent: { browser: "Chrome", os: "macOS", device: "desktop" } },
      } as TResponse;
      const anonymizedResponse = { ...mockResponses[0], id: "response2", meta: {} } as TResponse;

      const result = getResponsesJson(
        anonymizedSurvey,
        [olderResponse, anonymizedResponse],
        [["1. Question 1"]],
        [],
        false
      );

      expect(result[0]["Country"]).toBe("DE");
      expect(result[0]["Device Type"]).toBe("desktop");
      expect(result[1]["Country"]).toBe("");
      expect(result[1]["Device Type"]).toBe("");
    });

    test("an ingested number stays a number in the cell", () => {
      const surveyWithNumberField = asRead({
        ...mockSurvey,
        hiddenFields: { enabled: true, fieldIds: ["seats"] },
      });
      const response = {
        ...mockResponses[0],
        data: { ...mockResponses[0].data, seats: 12 },
      } as unknown as TResponse;

      const result = getResponsesJson(surveyWithNumberField, [response], [], [], false);

      expect(result[0]["seats"]).toBe(12);
    });

    test("an ingested cell is written under the field's name and read from its storage key", () => {
      // ENG-3233: the column header and the cell key are the same string, so this moves with
      // `extractSurveyDetails` or the row lands under a header the sheet does not have. Red on main,
      // which keyed the cell by `utm_campaign`.
      const renamed = {
        ...(mockSurvey as TSurvey),
        embeddedFields: [ingestedRow("Campaign", "utm_campaign")],
      } as TSurvey;
      const response = {
        ...mockResponses[0],
        data: { ...mockResponses[0].data, utm_campaign: "spring_sale" },
      } as unknown as TResponse;

      const result = getResponsesJson(renamed, [response], [], [], false);

      expect(result[0]["Campaign"]).toBe("spring_sale");
      expect(result[0]).not.toHaveProperty("utm_campaign");
    });

    test("an ingested field named like a fixed column does not take that column's cell", () => {
      // The `extractSurveyDetails` counterpart of this pins the header row; this pins the cells.
      // Both call sites need the same seed and neither guards the other: a row is one flat object
      // keyed by label, so an unseeded `Response ID` here would write the field's value over the
      // response's own id — under a header the sheet still has, holding the wrong value.
      const shadowing = {
        ...(mockSurvey as TSurvey),
        embeddedFields: [ingestedRow("Response ID", "resp_id")],
      } as TSurvey;
      const response = {
        ...mockResponses[0],
        data: { ...mockResponses[0].data, resp_id: "spring_sale" },
      } as unknown as TResponse;

      const result = getResponsesJson(shadowing, [response], [], [], false);

      expect(result[0]["Response ID"]).toBe("response1");
      expect(result[0]["Response ID (resp_id)"]).toBe("spring_sale");
    });

    test("a computed field the response never captured leaves an empty cell", () => {
      // resolveEmbeddedValue would substitute the declared default here — i.e. display a value the
      // respondent's run never produced. The export deliberately reads the raw slot instead.
      const surveyWithVariables = asRead({
        ...mockSurvey,
        variables: [{ id: "clx0000000000000000000v1", name: "score", type: "number", value: 5 }],
      });

      const result = getResponsesJson(
        surveyWithVariables,
        [{ ...mockResponses[0], variables: {} }] as TResponse[],
        [["1. Question 1"]],
        [],
        false
      );

      expect(result[0]).toHaveProperty("score");
      expect(result[0].score).toBeUndefined();
    });

    test("writes a captured computed value under the field's name, keyed by its storage key", () => {
      const surveyWithVariables = asRead({
        ...mockSurvey,
        variables: [{ id: "clx0000000000000000000v1", name: "score", type: "number", value: 5 }],
      });

      const result = getResponsesJson(
        surveyWithVariables,
        [{ ...mockResponses[0], variables: { clx0000000000000000000v1: 12 } }] as TResponse[],
        [["1. Question 1"]],
        [],
        false
      );

      expect(result[0].score).toBe(12);
    });

    test("should namespace person attributes for link surveys too", () => {
      const linkSurvey = { ...mockSurvey, type: "link" } as TSurvey;
      const responsesWithContact = [
        { ...mockResponses[0], contactAttributes: { plan: "pro", email: "linked@example.com" } },
      ] as TResponse[];
      const result = getResponsesJson(
        linkSurvey,
        responsesWithContact,
        [["1. Question 1"]],
        ["plan", "email"],
        false
      );
      expect(result[0]["person.plan"]).toBe("pro");
      expect(result[0]["person.email"]).toBe("linked@example.com");
    });

    test("should format the Timestamp in UTC when no time zone is provided", () => {
      const responsesWithFixedDate = [
        { ...mockResponses[0], createdAt: new Date("2026-01-01T20:00:00.000Z") },
      ] as TResponse[];
      const result = getResponsesJson(
        mockSurvey as TSurvey,
        responsesWithFixedDate,
        [["1. Question 1"]],
        [],
        false
      );
      expect(result[0]["Timestamp"]).toBe("2026-01-01 20:00:00 UTC");
    });

    test("should format the Timestamp in the configured time zone", () => {
      const responsesWithFixedDate = [
        { ...mockResponses[0], createdAt: new Date("2026-01-01T20:00:00.000Z") },
      ] as TResponse[];
      const result = getResponsesJson(
        mockSurvey as TSurvey,
        responsesWithFixedDate,
        [["1. Question 1"]],
        [],
        false,
        "Asia/Manila"
      );
      expect(result[0]["Timestamp"]).toBe("2026-01-02 04:00:00 GMT+8");
    });
  });

  describe("getResponseContactAttributes", () => {
    test("should extract contact attributes correctly", () => {
      const responses = [
        {
          contactAttributes: { email: "test1@example.com", name: "Test 1" },
          data: {},
          meta: {},
        },
        {
          contactAttributes: { email: "test2@example.com", name: "Test 2" },
          data: {},
          meta: {},
        },
      ];
      const result = getResponseContactAttributes(responses);
      expect(result.email).toContain("test1@example.com");
      expect(result.email).toContain("test2@example.com");
      expect(result.name).toContain("Test 1");
      expect(result.name).toContain("Test 2");
    });

    test("should handle empty responses", () => {
      const result = getResponseContactAttributes([]);
      expect(result).toEqual({});
    });
  });

  describe("getResponseMeta", () => {
    test("should extract meta data correctly", () => {
      const responses = [
        {
          contactAttributes: {},
          data: {},
          meta: {
            userAgent: { browser: "Chrome", os: "Windows" },
            country: "US",
          },
        },
        {
          contactAttributes: {},
          data: {},
          meta: {
            userAgent: { browser: "Firefox", os: "MacOS" },
            country: "UK",
          },
        },
      ];
      const result = getResponseMeta(responses);
      expect(result.browser).toContain("Chrome");
      expect(result.browser).toContain("Firefox");
      expect(result.os).toContain("Windows");
      expect(result.os).toContain("MacOS");
    });

    test("should extract URL data correctly", () => {
      const responses = [
        {
          contactAttributes: {},
          data: {},
          meta: {
            url: "https://example.com/page1",
            source: "direct",
          },
        },
        {
          contactAttributes: {},
          data: {},
          meta: {
            url: "https://test.com/page2?param=value",
            source: "google",
          },
        },
      ];
      const result = getResponseMeta(responses);
      expect(result.url).toEqual([]);
      expect(result.source).toContain("direct");
      expect(result.source).toContain("google");
    });

    test("should handle mixed meta data with URLs", () => {
      const responses = [
        {
          contactAttributes: {},
          data: {},
          meta: {
            userAgent: { browser: "Chrome", device: "desktop" },
            url: "https://formbricks.com/dashboard",
            country: "US",
          },
        },
        {
          contactAttributes: {},
          data: {},
          meta: {
            userAgent: { browser: "Safari", device: "mobile" },
            url: "https://formbricks.com/surveys/123",
            country: "UK",
          },
        },
      ];
      const result = getResponseMeta(responses);
      expect(result.browser).toContain("Chrome");
      expect(result.browser).toContain("Safari");
      expect(result.device).toContain("desktop");
      expect(result.device).toContain("mobile");
      expect(result.url).toEqual([]);
      expect(result.country).toContain("US");
      expect(result.country).toContain("UK");
    });

    test("should handle empty responses", () => {
      const result = getResponseMeta([]);
      expect(result).toEqual({});
    });

    test("should ignore empty or null URL values", () => {
      const responses = [
        {
          contactAttributes: {},
          data: {},
          meta: {
            url: "",
            source: "direct",
          },
        },
        {
          contactAttributes: {},
          data: {},
          meta: {
            url: null,
            source: "newsletter",
          },
        },
        {
          contactAttributes: {},
          data: {},
          meta: {
            url: "https://valid.com",
            source: "google",
          },
        },
      ];
      const result = getResponseMeta(responses as Pick<TResponse, "contactAttributes" | "data" | "meta">[]);
      expect(result.url).toEqual([]);
      expect(result.source).toEqual(expect.arrayContaining(["direct", "newsletter", "google"]));
    });
  });

  describe("getResponseHiddenFields", () => {
    const mockSurvey: Partial<TSurvey> = asRead({
      id: "survey1",
      name: "Test Survey",
      questions: [],
      type: "app",
      hiddenFields: { enabled: true, fieldIds: ["hidden1", "hidden2"] },
      createdAt: new Date(),
      updatedAt: new Date(),
      workspaceId: "env1",
      createdBy: "user1",
      status: "draft",
    });

    test("should extract hidden fields correctly", () => {
      const responses = [
        {
          contactAttributes: {},
          data: { hidden1: "value1", hidden2: "value2" },
          meta: {},
        },
        {
          contactAttributes: {},
          data: { hidden1: "value3", hidden2: "value4" },
          meta: {},
        },
      ];
      const result = getResponseHiddenFields(mockSurvey as TSurvey, responses);
      expect(result.hidden1).toContain("value1");
      expect(result.hidden1).toContain("value3");
      expect(result.hidden2).toContain("value2");
      expect(result.hidden2).toContain("value4");
    });

    test("should handle empty responses", () => {
      const result = getResponseHiddenFields(mockSurvey as TSurvey, []);
      expect(result).toEqual({
        hidden1: [],
        hidden2: [],
      });
    });

    test("a number field offers its stored values to the filter (ENG-3266)", () => {
      // These are the filter's value options. Under the old `typeof === "string"` gate a `number`
      // field collected nothing, so it appeared in the filter with an empty dropdown — filterable in
      // name only. `boolean` never reaches here: `surveys.ts` hardcodes its two options.
      const responses = [
        { contactAttributes: {}, data: { hidden1: 42, hidden2: "value2" }, meta: {} },
        { contactAttributes: {}, data: { hidden1: 0, hidden2: "value4" }, meta: {} },
      ];
      const result = getResponseHiddenFields(mockSurvey as TSurvey, responses);
      expect(result.hidden1).toContain("42");
      expect(result.hidden1).toContain("0");
    });
  });
});

describe("extractChoiceIdsFromResponse", () => {
  const multipleChoiceMultiQuestion = {
    id: "multi-choice-id",
    type: TSurveyElementTypeEnum.MultipleChoiceMulti as typeof TSurveyElementTypeEnum.MultipleChoiceMulti,
    headline: { default: "Select multiple options" },
    required: false,
    choices: [
      {
        id: "choice-1",
        label: { default: "Option 1", es: "Opción 1" },
      },
      {
        id: "choice-2",
        label: { default: "Option 2", es: "Opción 2" },
      },
      {
        id: "choice-3",
        label: { default: "Option 3", es: "Opción 3" },
      },
    ],
    shuffleOption: "none" as const,
  };

  const multipleChoiceSingleQuestion = {
    id: "single-choice-id",
    type: TSurveyElementTypeEnum.MultipleChoiceSingle as typeof TSurveyElementTypeEnum.MultipleChoiceSingle,
    headline: { default: "Select one option" },
    required: false,
    choices: [
      {
        id: "choice-a",
        label: { default: "Choice A", fr: "Choix A" },
      },
      {
        id: "choice-b",
        label: { default: "Choice B", fr: "Choix B" },
      },
    ],
    shuffleOption: "none" as const,
  };

  const textQuestion = {
    id: "text-id",
    type: TSurveyElementTypeEnum.OpenText as typeof TSurveyElementTypeEnum.OpenText,
    headline: { default: "What do you think?" },
    required: false,
    inputType: "text" as const,
    charLimit: { enabled: false, min: 0, max: 0 },
  };

  describe("multipleChoiceMulti questions", () => {
    test("should extract choice IDs from array response with default language", () => {
      const responseValue = ["Option 1", "Option 3"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual(["choice-1", "choice-3"]);
    });

    test("should extract choice IDs from array response with specific language", () => {
      const responseValue = ["Opción 1", "Opción 2"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "es");

      expect(result).toEqual(["choice-1", "choice-2"]);
    });

    test("should fall back to checking all language values when exact language match fails", () => {
      const responseValue = ["Opción 1", "Option 2"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual(["choice-1", "choice-2"]);
    });

    test("should render other option when non-matching choice is selected", () => {
      const responseValue = ["Option 1", "Non-existent option", "Option 3"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual(["choice-1", "other", "choice-3"]);
    });

    test("should return empty array for empty response", () => {
      const responseValue: string[] = [];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual([]);
    });
  });

  describe("multipleChoiceSingle questions", () => {
    test("should extract choice ID from string response with default language", () => {
      const responseValue = "Choice A";
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceSingleQuestion, "default");

      expect(result).toEqual(["choice-a"]);
    });

    test("should extract choice ID from string response with specific language", () => {
      const responseValue = "Choix B";
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceSingleQuestion, "fr");

      expect(result).toEqual(["choice-b"]);
    });

    test("should fall back to checking all language values for single choice", () => {
      const responseValue = "Choix A";
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceSingleQuestion, "default");

      expect(result).toEqual(["choice-a"]);
    });

    test("should return empty array for empty string response", () => {
      const responseValue = "";
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceSingleQuestion, "default");

      expect(result).toEqual([]);
    });
  });

  describe("edge cases", () => {
    test("should return empty array for non-multiple choice questions", () => {
      const responseValue = "Some text response";
      const result = extractChoiceIdsFromResponse(responseValue, textQuestion, "default");

      expect(result).toEqual([]);
    });

    test("should handle missing language parameter by defaulting to 'default'", () => {
      const responseValue = "Option 1";
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion);

      expect(result).toEqual(["choice-1"]);
    });

    test("should handle numeric or other types by returning empty array", () => {
      const responseValue = 123;
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual([]);
    });

    test("should handle object responses by returning empty array", () => {
      const responseValue = { invalid: "object" };
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "default");

      expect(result).toEqual([]);
    });
  });

  describe("language handling", () => {
    test("should use provided language parameter", () => {
      const responseValue = ["Opción 1"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, "es");

      expect(result).toEqual(["choice-1"]);
    });

    test("should handle null language parameter by defaulting to 'default'", () => {
      const responseValue = ["Option 1"];
      const result = extractChoiceIdsFromResponse(
        responseValue,
        multipleChoiceMultiQuestion,
        null as unknown as Parameters<typeof extractChoiceIdsFromResponse>[2]
      );

      expect(result).toEqual(["choice-1"]);
    });

    test("should handle undefined language parameter by defaulting to 'default'", () => {
      const responseValue = ["Option 1"];
      const result = extractChoiceIdsFromResponse(responseValue, multipleChoiceMultiQuestion, undefined);

      expect(result).toEqual(["choice-1"]);
    });
  });
});
