import "server-only";
import { Prisma } from "@formbricks/database/prisma";
import { TEmbeddedDataType } from "@formbricks/types/embedded-data";
import {
  RESERVED_FIELD_CATALOG,
  getComputedEmbeddedFields,
  getIngestedEmbeddedFields,
  getSurveyEmbeddedFields,
  listShadowingNames,
} from "@formbricks/types/embedded-data-resolver";
import { InvalidInputError } from "@formbricks/types/errors";
import { TResponseFilterCriteria, TResponseStatusFilter } from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { buildShownFilterClauses } from "./shown-filter";

type TTypedFieldFilterCondition = NonNullable<TResponseFilterCriteria["reserved"]>[string];

type TReservedFilterLocator = { kind: "meta"; path: string[] } | { kind: "ttcTotalMs" };

/**
 * Where each filterable reserved field physically lives on the Response row. The catalog carries
 * typed `read` accessors instead of path strings on purpose (see the rationale in
 * embedded-data-resolver.ts), so the DB layer owns this map; the anti-drift test in utils.test.ts
 * pins that every entry `getReservedFilterEntries` can offer has a locator. `durationSeconds` is
 * the one computed entry — it filters the stored `ttc._total` milliseconds through windows that
 * reproduce the read seam's `Math.round(ms / 1000)` projection exactly.
 */
export const RESERVED_FILTER_LOCATORS: Record<string, TReservedFilterLocator> = {
  source: { kind: "meta", path: ["source"] },
  url: { kind: "meta", path: ["url"] },
  country: { kind: "meta", path: ["country"] },
  action: { kind: "meta", path: ["action"] },
  browser: { kind: "meta", path: ["userAgent", "browser"] },
  os: { kind: "meta", path: ["userAgent", "os"] },
  deviceType: { kind: "meta", path: ["userAgent", "device"] },
  ipAddress: { kind: "meta", path: ["ipAddress"] },
  pagePath: { kind: "meta", path: ["pagePath"] },
  pageReferrer: { kind: "meta", path: ["pageReferrer"] },
  utmSource: { kind: "meta", path: ["utmSource"] },
  utmMedium: { kind: "meta", path: ["utmMedium"] },
  utmCampaign: { kind: "meta", path: ["utmCampaign"] },
  utmTerm: { kind: "meta", path: ["utmTerm"] },
  utmContent: { kind: "meta", path: ["utmContent"] },
  screenWidth: { kind: "meta", path: ["screenWidth"] },
  screenHeight: { kind: "meta", path: ["screenHeight"] },
  viewportWidth: { kind: "meta", path: ["viewportWidth"] },
  viewportHeight: { kind: "meta", path: ["viewportHeight"] },
  timezone: { kind: "meta", path: ["timezone"] },
  locale: { kind: "meta", path: ["locale"] },
  visitPagesViewed: { kind: "meta", path: ["visitPagesViewed"] },
  visitUniquePagesViewed: { kind: "meta", path: ["visitUniquePagesViewed"] },
  visitTimeOnSite: { kind: "meta", path: ["visitTimeOnSite"] },
  visitEntryReferrer: { kind: "meta", path: ["visitEntryReferrer"] },
  visitUrls: { kind: "meta", path: ["visitUrls"] },
  openedByCreativeId: { kind: "meta", path: ["openedByCreativeId"] },
  openedByCreativeName: { kind: "meta", path: ["openedByCreativeName"] },
  durationSeconds: { kind: "ttcTotalMs" },
};

const mkJsonColumnFilter = (
  column: "meta" | "variables",
  filter: Prisma.ResponseWhereInput["meta"]
): Prisma.ResponseWhereInput => (column === "meta" ? { meta: filter } : { variables: filter });

// Negated text ops share their Prisma key with the positive op and wrap in NOT.
const TEXT_OP_TO_PRISMA: Record<string, { key: string; negated: boolean }> = {
  contains: { key: "string_contains", negated: false },
  doesNotContain: { key: "string_contains", negated: true },
  startsWith: { key: "string_starts_with", negated: false },
  doesNotStartWith: { key: "string_starts_with", negated: true },
  endsWith: { key: "string_ends_with", negated: false },
  doesNotEndWith: { key: "string_ends_with", negated: true },
};

const COMPARISON_OP_TO_PRISMA: Record<string, string> = {
  lessThan: "lt",
  lessEqual: "lte",
  greaterThan: "gt",
  greaterEqual: "gte",
};

/**
 * A half-open `[min, max)` window on a JSON path: what a date-only filter value means against a
 * column that stores days and instants alike (ENG-3232). `notInRange` treats an absent value as a
 * match, like `notEquals`.
 *
 * Date fields only. The bounds are strings — `ZResponseFilterCriteria` types them that way so an
 * ISO day and an ISO instant compare lexicographically the way they do in time — and only
 * `buildDateFieldCondition` ever produces this op, from a `date` field. A number stored in JSON
 * would be compared against those strings across JSON types rather than by value, so a numeric
 * range would quietly select the wrong rows; numbers filter through `gt`/`gte`/`lt`/`lte` instead,
 * which `buildTypedFieldCondition` gives them with a real numeric operand. Anything else could only
 * have been crafted by hand, so it fails closed.
 */
const buildJsonPathRangeCondition = (
  column: "meta" | "variables",
  path: string[],
  val: Extract<TTypedFieldFilterCondition, { op: "inRange" | "notInRange" }>,
  dataType: TEmbeddedDataType
): Prisma.ResponseWhereInput | null => {
  if (dataType !== "date") return null;

  if (val.op === "inRange") {
    return {
      AND: [
        mkJsonColumnFilter(column, { path, gte: val.min }),
        mkJsonColumnFilter(column, { path, lt: val.max }),
      ],
    };
  }

  return {
    OR: [
      mkJsonColumnFilter(column, { path, lt: val.min }),
      mkJsonColumnFilter(column, { path, gte: val.max }),
      mkJsonColumnFilter(column, { path, equals: Prisma.DbNull }),
    ],
  };
};

/**
 * One typed condition → one Prisma JSON-path filter on `meta` or `variables`. `notEquals` and
 * `isNotSet` treat an absent value as a match (same stance as the `data` branch below). Ops that
 * don't fit the field's dataType — text ops on anything but a string, comparisons on a boolean or
 * string — emit nothing: fail closed rather than querying a shape the value can never have.
 */
const buildJsonPathCondition = (
  column: "meta" | "variables",
  path: string[],
  val: TTypedFieldFilterCondition,
  dataType: TEmbeddedDataType
): Prisma.ResponseWhereInput | null => {
  if (val.op === "isSet") return mkJsonColumnFilter(column, { path, not: Prisma.DbNull });
  if (val.op === "isNotSet") return mkJsonColumnFilter(column, { path, equals: Prisma.DbNull });
  if (val.op === "equals") return mkJsonColumnFilter(column, { path, equals: val.value });
  if (val.op === "notEquals") {
    return {
      OR: [
        mkJsonColumnFilter(column, { path, not: val.value }),
        mkJsonColumnFilter(column, { path, equals: Prisma.DbNull }),
      ],
    };
  }

  if (val.op === "inRange" || val.op === "notInRange") {
    return buildJsonPathRangeCondition(column, path, val, dataType);
  }

  if (!("value" in val)) return null;

  const textOp = TEXT_OP_TO_PRISMA[val.op];
  if (textOp) {
    if (dataType !== "string") return null;
    // The dynamic Prisma key needs one cast; the three keys above are all valid string filters.
    const filter = mkJsonColumnFilter(column, {
      path,
      [textOp.key]: val.value,
    } as Prisma.ResponseWhereInput["meta"]);
    return textOp.negated ? { NOT: filter } : filter;
  }

  const comparisonKey = COMPARISON_OP_TO_PRISMA[val.op];
  if (!comparisonKey) return null;
  if (dataType !== "number" && dataType !== "date") return null;
  return mkJsonColumnFilter(column, {
    path,
    [comparisonKey]: val.value,
  } as Prisma.ResponseWhereInput["meta"]);
};

/**
 * `durationSeconds` filters in seconds against `ttc._total`, which stores milliseconds. The read
 * seam projects `Math.round(ms / 1000)`, so second `s` covers ms in [s*1000-500, s*1000+500) — the
 * windows below make DB filtering agree with the projected value at every boundary. `ttc._total`
 * only exists on finished responses, so partials never match (except via `isNotSet`).
 */
const buildDurationSecondsCondition = (val: TTypedFieldFilterCondition): Prisma.ResponseWhereInput | null => {
  const path = ["_total"];
  if (val.op === "isSet") return { ttc: { path, not: Prisma.DbNull } };
  if (val.op === "isNotSet") return { ttc: { path, equals: Prisma.DbNull } };
  if (!("value" in val)) return null;
  const seconds = Number(val.value);
  if (!Number.isFinite(seconds)) return null;
  const lower = seconds * 1000 - 500;
  const upper = seconds * 1000 + 500;
  switch (val.op) {
    case "equals":
      return { AND: [{ ttc: { path, gte: lower } }, { ttc: { path, lt: upper } }] };
    case "notEquals":
      return {
        OR: [
          { ttc: { path, lt: lower } },
          { ttc: { path, gte: upper } },
          { ttc: { path, equals: Prisma.DbNull } },
        ],
      };
    case "greaterThan":
      return { ttc: { path, gte: upper } };
    case "greaterEqual":
      return { ttc: { path, gte: lower } };
    case "lessThan":
      return { ttc: { path, lt: lower } };
    case "lessEqual":
      return { ttc: { path, lt: upper } };
    default:
      return null;
  }
};

/**
 * The `reserved` criteria group → conditions. Fails closed (ENG-1848): a name the survey's declared
 * fields or element ids shadow filters the declared value elsewhere, never the reserved read — and
 * an unknown name emits nothing. `Object.hasOwn` because the keys come from a z.record: a crafted
 * `__proto__`/`constructor` key must not resolve a locator through the prototype chain.
 */
const buildReservedConditions = (
  survey: TSurvey,
  reserved: NonNullable<TResponseFilterCriteria["reserved"]>
): Prisma.ResponseWhereInput[] => {
  const elementIds = getElementsFromBlocks(survey.blocks).map((element) => element.id);
  const shadowed = new Set(listShadowingNames(getSurveyEmbeddedFields(survey), elementIds));
  const catalogEntriesByName = new Map(RESERVED_FIELD_CATALOG.map((entry) => [entry.name, entry]));
  const conditions: Prisma.ResponseWhereInput[] = [];

  Object.entries(reserved).forEach(([name, val]) => {
    if (shadowed.has(name)) return;
    if (!Object.hasOwn(RESERVED_FILTER_LOCATORS, name)) return;
    const entry = catalogEntriesByName.get(name);
    if (!entry) return;
    const locator = RESERVED_FILTER_LOCATORS[name];
    const condition =
      locator.kind === "ttcTotalMs"
        ? buildDurationSecondsCondition(val)
        : buildJsonPathCondition("meta", locator.path, val, entry.dataType);
    if (condition) conditions.push(condition);
  });

  return conditions;
};

/** The `variables` group → conditions. Keys are computed-field storageKeys; anything else emits nothing. */
/**
 * "is True" / "is False" on a computed true/false field (ENG-6973). The engines store a real boolean,
 * and the filter sends the spelling `"true"` / `"false"`, which a JSON `equals` would never match
 * against it; a value written as the string (by an API caller) still matches too.
 */
const buildBooleanVariableCondition = (
  path: string[],
  val: TTypedFieldFilterCondition
): Prisma.ResponseWhereInput | null => {
  if ((val.op !== "equals" && val.op !== "notEquals") || (val.value !== "true" && val.value !== "false")) {
    return null;
  }
  const spellings = [val.value === "true", val.value];
  if (val.op === "equals") {
    return { OR: spellings.map((equals) => mkJsonColumnFilter("variables", { path, equals })) };
  }
  return {
    OR: [
      { AND: spellings.map((not) => mkJsonColumnFilter("variables", { path, not })) },
      mkJsonColumnFilter("variables", { path, equals: Prisma.DbNull }),
    ],
  };
};

const buildVariableConditions = (
  survey: TSurvey,
  variables: NonNullable<TResponseFilterCriteria["variables"]>
): Prisma.ResponseWhereInput[] => {
  const computedFieldsByKey = new Map(
    getComputedEmbeddedFields(survey).map((field) => [field.link.storageKey, field])
  );
  const conditions: Prisma.ResponseWhereInput[] = [];

  Object.entries(variables).forEach(([storageKey, val]) => {
    const field = computedFieldsByKey.get(storageKey);
    if (!field) return;
    const { dataType } = field.field;
    const isBooleanComparison = dataType === "boolean" && (val.op === "equals" || val.op === "notEquals");
    const condition = isBooleanComparison
      ? buildBooleanVariableCondition([storageKey], val)
      : buildJsonPathCondition("variables", [storageKey], val, dataType);
    if (condition) conditions.push(condition);
  });

  return conditions;
};

/**
 * The `data` keys a range may name: ingested **date** fields, for the reason
 * {@link buildJsonPathRangeCondition} gives — string bounds cannot range a stored number.
 *
 * The group is shared. `processIngestedFilters` writes ingested storageKeys into it beside the
 * element ids that have always lived there, so unlike `variables` it cannot simply drop keys it
 * does not recognise — an element id is a legitimate key that no embedded field answers for.
 */
const rangeableIngestedDataKeys = (survey: TSurvey): ReadonlySet<string> =>
  new Set(
    getIngestedEmbeddedFields(survey)
      .filter(({ field }) => field.dataType === "date")
      .map(({ link }) => link.storageKey)
  );

/**
 * A half-open `[min, max)` window on the `data` column, or nothing at all.
 *
 * Same rule as {@link buildJsonPathRangeCondition} on `meta` and `variables`: a range is only
 * meaningful over an ordered type, and the real producer never asks for another — `inRange` and
 * `notInRange` reach `data` only through `processIngestedFilters`, which builds them from
 * `buildTypedFieldCondition`. So this answers crafted criteria, and it answers them by failing
 * closed rather than by lexicographically ranging a string. `notInRange` lets an absent value
 * match, like `notEquals` in the same switch.
 */
const buildDataRangeConditions = (
  key: string,
  val: Extract<NonNullable<TResponseFilterCriteria["data"]>[string], { op: "inRange" | "notInRange" }>,
  rangeableKeys: ReadonlySet<string>
): Prisma.ResponseWhereInput[] => {
  if (!rangeableKeys.has(key)) return [];

  if (val.op === "inRange") {
    return [{ AND: [{ data: { path: [key], gte: val.min } }, { data: { path: [key], lt: val.max } }] }];
  }

  return [
    {
      OR: [
        { data: { path: [key], lt: val.min } },
        { data: { path: [key], gte: val.max } },
        { data: { path: [key], equals: Prisma.DbNull } },
      ],
    },
  ];
};

/**
 * The ENG-1848 criteria groups as ready-to-push clauses. Both branches live here rather than in
 * `buildWhereClause`, which sat exactly at the cognitive-complexity limit before this feature —
 * even two plain `if`s there tip it over.
 */
const buildEmbeddedDataFilterClauses = (
  survey: TSurvey,
  filterCriteria?: TResponseFilterCriteria
): Prisma.ResponseWhereInput[] => {
  const clauses: Prisma.ResponseWhereInput[] = [];

  if (filterCriteria?.reserved) {
    clauses.push({ AND: buildReservedConditions(survey, filterCriteria.reserved) });
  }
  if (filterCriteria?.variables) {
    clauses.push({ AND: buildVariableConditions(survey, filterCriteria.variables) });
  }

  return clauses;
};

const createFilterTags = (tags: TResponseFilterCriteria["tags"]) => {
  if (!tags) return [];

  const filterTags: (Prisma.ResponseWhereInput | Prisma.ResponseWhereInput[])[] = [];

  if (tags?.applied) {
    const appliedTags = tags.applied.map((name) => ({
      tags: {
        some: {
          tag: {
            name,
          },
        },
      },
    }));
    filterTags.push(appliedTags);
  }

  if (tags?.appliedAny?.length) {
    filterTags.push({ tags: { some: { tag: { name: { in: tags.appliedAny } } } } });
  }

  if (tags?.notApplied) {
    const notAppliedTags = {
      tags: {
        every: {
          tag: {
            name: {
              notIn: tags.notApplied,
            },
          },
        },
      },
    };

    filterTags.push(notAppliedTags);
  }

  return filterTags.flat();
};

/**
 * Upper bound on the filter clauses a single buildWhereClause call may emit.
 *
 * The "Other" branches below scale with the element's choice count, which has no maximum
 * (ZSurveyElementChoice is `.min(2)` only), so an unbounded predicate is a denial-of-service
 * vector — a low-privilege request could allocate until the process died (ENG-3161).
 *
 * The budget is per CALL, not per branch: `filterCriteria.data` is a record whose keys are each
 * iterated below, so a per-branch cap would simply be multiplied by the key count.
 *
 * 10k clauses is ~30k bind parameters (each probe binds key + index + label), comfortably under
 * PostgreSQL's 65535 ceiling.
 *
 * What that buys is not one number. The multi branch charges `positions x (distinct labels + 1)`, and
 * a label exists per language, so the reachable choice count falls roughly as `10000 / (L x c)`: ~99
 * choices monolingual, but only ~40 trilingual, and a 45-option country list in five languages does
 * not fit. Deduplicating labels below recovers the common case where a choice is left untranslated
 * and the same text repeats across languages, but not one that is genuinely translated five ways.
 * Sharing the budget across keys means `tags` or a second `data` key takes from the same allowance.
 *
 * A filter past the budget throws, which the analysis actions surface as a hard error. That is the
 * deliberate trade against ENG-3161's unbounded predicate, but it is reachable by a legitimate survey
 * rather than only by an abusive one — see the PR's open gaps.
 */
const MAX_FILTER_CLAUSES = 10_000;

/**
 * Extra array positions probed beyond the element's choice count when testing for an "Other" write-in.
 *
 * Sized for the two ways a stored answer outgrows `choices.length` in practice — a handful of repeated
 * entries, or a few choices deleted from a running survey after the answer was collected. It is a
 * mitigation, not a proof: see the probe itself for what remains uncovered.
 */
const OTHER_WRITE_IN_PROBE_SLACK = 8;

/**
 * One call's clause allowance. The returned `spend` charges against it and refuses the filter once
 * it is exhausted. Kept out of buildWhereClause so the budget is a self-contained concern rather
 * than more branching inside an already-large builder.
 */
const createClauseBudget = (): ((count: number) => void) => {
  let remaining = MAX_FILTER_CLAUSES;

  return (count: number): void => {
    remaining -= count;
    if (remaining < 0) {
      throw new InvalidInputError("This response filter is too large to evaluate");
    }
  };
};

/**
 * "At least one entry of this multi answer is not one of `predefinedLabels`": the Other write-in, which
 * is stored as the typed text. Prisma's JSON filters have no subset operator, so each array position
 * is probed by numeric path segment (see the includesOne branch for why the probe has slack).
 */
const writeInEntryClause = (
  key: string,
  choiceCount: number,
  predefinedLabels: readonly string[],
  spend: (count: number) => void
): Prisma.ResponseWhereInput => {
  const positions = choiceCount + OTHER_WRITE_IN_PROBE_SLACK;
  spend(positions * (predefinedLabels.length + 1));
  return {
    OR: Array.from({ length: positions }, (_unused, index) => ({
      AND: [
        { data: { path: [key, String(index)], not: Prisma.DbNull } },
        ...predefinedLabels.map((label) => ({ data: { path: [key, String(index)], not: label } })),
      ],
    })),
  };
};

/**
 * "Includes all" of a multi answer. Other is never stored as such: the answer holds the typed text
 * instead, so Other among the values means "has a write-in", next to the predefined values it must
 * contain.
 */
const includesAllClauses = (
  key: string,
  element: ReturnType<typeof getElementsFromBlocks>[number] | undefined,
  values: (string | number)[],
  spend: (count: number) => void
): Prisma.ResponseWhereInput[] => {
  if (element?.type !== "multipleChoiceMulti") return [{ data: { path: [key], array_contains: values } }];
  const otherChoice = element.choices.find((choice) => choice.id === "other");
  const otherLabels = new Set(otherChoice ? Object.values(otherChoice.label) : []);
  const predefined = values.filter((value) => !otherLabels.has(String(value)));
  if (predefined.length === values.length) return [{ data: { path: [key], array_contains: values } }];

  const predefinedLabels = [
    ...new Set(
      element.choices
        .filter((choice) => choice.id !== "other")
        .flatMap((choice) => Object.values(choice.label))
    ),
  ];
  return [
    ...(predefined.length > 0 ? [{ data: { path: [key], array_contains: predefined } }] : []),
    writeInEntryClause(key, element.choices.length, predefinedLabels, spend),
  ];
};

/** Whether the filter selects Low quality responses, by `outcome` or as one of several `statuses`. */
export const selectsLowQuality = (filterCriteria: TResponseFilterCriteria | undefined): boolean =>
  Boolean(filterCriteria?.outcome) || Boolean(filterCriteria?.statuses?.includes("lowQuality"));

/**
 * The outcome the filter selects, or (for the export) only responses without one. A filter that selects
 * Low quality through `statuses` is not narrowed further: that choice wins over leaving them out.
 */
const buildOutcomeCondition = (
  filterCriteria: TResponseFilterCriteria | undefined
): Prisma.ResponseWhereInput | null => {
  if (filterCriteria?.outcome) return { outcome: filterCriteria.outcome };
  return filterCriteria?.excludeLowQuality && !selectsLowQuality(filterCriteria) ? { outcome: null } : null;
};

const STATUS_CONDITIONS: Record<TResponseStatusFilter, Prisma.ResponseWhereInput> = {
  complete: { finished: true },
  partial: { finished: false },
  lowQuality: { outcome: "lowQuality" },
};

const buildStatusesCondition = (
  filterCriteria: TResponseFilterCriteria | undefined
): Prisma.ResponseWhereInput | null =>
  filterCriteria?.statuses?.length
    ? { OR: filterCriteria.statuses.map((status) => STATUS_CONDITIONS[status]) }
    : null;

/** The time range the filter selects: `max` is the latest, `min` the earliest creation time. */
const buildCreatedAtCondition = (
  filterCriteria: TResponseFilterCriteria | undefined
): Prisma.ResponseWhereInput | null => {
  if (!filterCriteria?.createdAt) return null;
  const createdAt: { lte?: Date; gte?: Date } = {};
  if (filterCriteria.createdAt.max) createdAt.lte = filterCriteria.createdAt.max;
  if (filterCriteria.createdAt.min) createdAt.gte = filterCriteria.createdAt.min;
  return { createdAt };
};

export const buildWhereClause = (survey: TSurvey, filterCriteria?: TResponseFilterCriteria) => {
  const whereClause: Prisma.ResponseWhereInput["AND"] = [];

  const spend = createClauseBudget();

  if (filterCriteria?.finished !== undefined) {
    whereClause.push({
      finished: filterCriteria?.finished,
    });
  }

  const outcomeCondition = buildOutcomeCondition(filterCriteria);
  if (outcomeCondition) {
    whereClause.push(outcomeCondition);
  }

  const statusesCondition = buildStatusesCondition(filterCriteria);
  if (statusesCondition) {
    whereClause.push(statusesCondition);
  }

  const createdAtCondition = buildCreatedAtCondition(filterCriteria);
  if (createdAtCondition) {
    whereClause.push(createdAtCondition);
  }

  if (filterCriteria?.tags) {
    // `applied` expands to one relation subquery per tag, so charge what was actually emitted.
    const tagFilters = createFilterTags(filterCriteria.tags);
    spend(tagFilters.length);

    whereClause.push({
      AND: tagFilters,
    });
  }

  if (filterCriteria?.contactAttributes) {
    const contactAttributes: Prisma.ResponseWhereInput[] = [];

    Object.entries(filterCriteria.contactAttributes).forEach(([key, val]) => {
      switch (val.op) {
        case "equals":
          contactAttributes.push({
            contactAttributes: {
              path: [key],
              equals: val.value,
            },
          });
          break;
        case "notEquals":
          contactAttributes.push({
            contactAttributes: {
              path: [key],
              not: val.value,
            },
          });
          break;
      }
    });

    whereClause.push({
      AND: contactAttributes,
    });
  }

  if (filterCriteria?.meta) {
    const meta: Prisma.ResponseWhereInput[] = [];

    Object.entries(filterCriteria.meta).forEach(([key, val]) => {
      let updatedKey: string[] = [];
      if (["browser", "os", "device"].includes(key)) {
        updatedKey = ["userAgent", key];
      } else {
        updatedKey = [key];
      }

      switch (val.op) {
        case "equals":
          meta.push({
            meta: {
              path: updatedKey,
              equals: val.value,
            },
          });
          break;
        case "notEquals":
          meta.push({
            meta: {
              path: updatedKey,
              not: val.value,
            },
          });
          break;
        case "contains":
          meta.push({
            meta: {
              path: updatedKey,
              string_contains: val.value,
            },
          });
          break;
        case "doesNotContain":
          meta.push({
            NOT: {
              meta: {
                path: updatedKey,
                string_contains: val.value,
              },
            },
          });
          break;
        case "startsWith":
          meta.push({
            meta: {
              path: updatedKey,
              string_starts_with: val.value,
            },
          });
          break;
        case "doesNotStartWith":
          meta.push({
            NOT: {
              meta: {
                path: updatedKey,
                string_starts_with: val.value,
              },
            },
          });
          break;
        case "endsWith":
          meta.push({
            meta: {
              path: updatedKey,
              string_ends_with: val.value,
            },
          });
          break;
        case "doesNotEndWith":
          meta.push({
            NOT: {
              meta: {
                path: updatedKey,
                string_ends_with: val.value,
              },
            },
          });
          break;
      }
    });

    whereClause.push({
      AND: meta,
    });
  }

  if (filterCriteria?.others) {
    const others: Prisma.ResponseWhereInput[] = [];

    Object.entries(filterCriteria.others).forEach(([key, val]) => {
      switch (val.op) {
        case "equals":
          others.push({
            [key.toLocaleLowerCase()]: val.value,
          });
          break;
        case "notEquals":
          others.push({
            [key.toLocaleLowerCase()]: {
              not: val.value,
            },
          });
          break;
        case "in":
          others.push({
            [key.toLocaleLowerCase()]: {
              in: val.value,
            },
          });
          break;
      }
    });
    whereClause.push({
      AND: others,
    });
  }

  whereClause.push(
    ...buildEmbeddedDataFilterClauses(survey, filterCriteria),
    ...buildShownFilterClauses(survey, filterCriteria?.shown, spend)
  );

  // `dataAnd` carries further conditions on keys `data` already holds; every one of them must hold.
  const dataEntries = [
    ...Object.entries(filterCriteria?.data ?? {}),
    ...(filterCriteria?.dataAnd ?? []).map(({ key, condition }) => [key, condition] as const),
  ];
  if (dataEntries.length > 0) {
    const data: Prisma.ResponseWhereInput[] = [];
    const rangeableIngestedKeys = rangeableIngestedDataKeys(survey);

    dataEntries.forEach(([key, val]) => {
      const elements = getElementsFromBlocks(survey.blocks);
      const element = elements.find((element) => element.id === key);

      switch (val.op) {
        case "submitted":
          data.push({
            data: {
              path: [key],
              not: Prisma.DbNull,
            },
          });
          break;
        case "filledOut":
          data.push({
            data: {
              path: [key],
              not: [],
            },
          });
          break;
        case "skipped":
          data.push({
            OR: [
              {
                data: {
                  path: [key],
                  equals: Prisma.DbNull,
                },
              },
              {
                data: {
                  path: [key],
                  equals: "",
                },
              },
              {
                data: {
                  path: [key],
                  equals: [],
                },
              },
            ],
          });
          break;
        case "equals":
          data.push({
            data: {
              path: [key],
              equals: val.value,
            },
          });
          break;
        case "notEquals":
          data.push({
            OR: [
              {
                data: {
                  path: [key],
                  not: val.value,
                },
              },
              {
                data: {
                  path: [key],
                  equals: Prisma.DbNull,
                },
              },
            ],
          });
          break;
        case "lessThan":
          data.push({
            data: {
              path: [key],
              lt: val.value,
            },
          });
          break;
        case "lessEqual":
          data.push({
            data: {
              path: [key],
              lte: val.value,
            },
          });
          break;
        case "greaterThan":
          data.push({
            data: {
              path: [key],
              gt: val.value,
            },
          });
          break;
        case "greaterEqual":
          data.push({
            data: {
              path: [key],
              gte: val.value,
            },
          });
          break;
        case "inRange":
        case "notInRange":
          data.push(...buildDataRangeConditions(key, val, rangeableIngestedKeys));
          break;
        case "includesAll":
          data.push(...includesAllClauses(key, element, val.value, spend));
          break;
        case "includesOne": {
          const values = new Set(val.value.map((v) => v.toString()));
          const otherChoice =
            element && (element.type === "multipleChoiceMulti" || element.type === "multipleChoiceSingle")
              ? element.choices.find((choice) => choice.id === "other")
              : null;

          if (
            element &&
            (element.type === "multipleChoiceMulti" || element.type === "multipleChoiceSingle") &&
            element.choices.map((choice) => choice.id).includes("other") &&
            otherChoice &&
            values.has(otherChoice.label.default)
          ) {
            // Deduplicated: a choice left untranslated carries the same text under every language
            // key, and `{ not: label }` twice is the same clause twice. Charging it once per language
            // spent the budget on nothing (ENG-3161 review).
            const predefinedLabelSet = new Set<string>();

            element.choices.forEach((choice) => {
              Object.values(choice.label).forEach((label) => {
                if (!values.has(label)) {
                  predefinedLabelSet.add(label);
                }
              });
            });

            const predefinedLabels = [...predefinedLabelSet];

            if (element.type === "multipleChoiceMulti") {
              // A multi answer is a string[] of the chosen labels, with the "Other" write-in stored
              // as the raw typed text. "Other was chosen" therefore means: at least one entry is
              // not a predefined label. Prisma's JSON filters have no subset operator, so each
              // array position is probed by numeric path segment; positions past the end extract to
              // SQL NULL, so unanswered and empty ([]) responses correctly do not match.
              //
              // A well-formed answer holds at most one entry per choice, so `choices.length` would
              // cover it. Stored answers are not guaranteed well-formed, and both ways past that end
              // with the write-in at an unprobed index — silently narrowing what the pre-ENG-3161
              // predicate matched:
              //
              //   - nothing enforces uniqueness (`ZResponseDataValue` is `z.array(z.string())`; some
              //     write paths cap its length, none its contents), so
              //     `["A0","A0","A0","A0","write-in"]` is accepted on a 3-choice element;
              //   - deleting choices from a running survey shrinks `choices.length` while the already
              //     collected answers keep their original length.
              //
              // The slack covers both at realistic sizes. It cannot close the class — an array with
              // more than SLACK duplicates still escapes — because a positional probe cannot bound an
              // unbounded array. Bounding the stored array on write is the real fix and its own ticket.
              data.push(writeInEntryClause(key, element.choices.length, predefinedLabels, spend));
            } else {
              // A single answer is a scalar string, so "not any predefined label" is directly
              // expressible and stays linear in the label count.
              spend(predefinedLabels.length);

              data.push({
                AND: predefinedLabels.map((label) => ({
                  NOT: {
                    data: {
                      path: [key],
                      equals: label,
                    },
                  },
                })),
              });
            }
          } else {
            // Two clauses per selected value: the array shape and the scalar shape.
            spend(val.value.length * 2);

            data.push({
              OR: val.value.map((value: string | number) => ({
                OR: [
                  {
                    data: {
                      path: [key],
                      array_contains: [value],
                    },
                  },
                  {
                    data: {
                      path: [key],
                      equals: value,
                    },
                  },
                ],
              })),
            });
          }

          break;
        }
        case "uploaded":
          data.push({
            data: {
              path: [key],
              not: "skipped",
            },
          });
          break;
        case "notUploaded":
          data.push({
            OR: [
              {
                data: {
                  path: [key],
                  equals: "skipped",
                },
              },
              {
                data: {
                  path: [key],
                  equals: Prisma.DbNull,
                },
              },
            ],
          });
          break;
        case "clicked":
          data.push({
            data: {
              path: [key],
              equals: "clicked",
            },
          });
          break;
        case "accepted":
          data.push({
            data: {
              path: [key],
              equals: "accepted",
            },
          });
          break;
        case "booked":
          data.push({
            data: {
              path: [key],
              equals: "booked",
            },
          });
          break;
        case "matrix": {
          const rows = Object.entries(val.value);
          spend(rows.length);
          for (const [rowLabel, column] of rows) {
            data.push({ data: { path: [key, rowLabel], equals: column } });
          }
          break;
        }
        // Text ops for string-typed ingested Embedded Data fields (ENG-1848).
        case "contains":
          data.push({
            data: {
              path: [key],
              string_contains: val.value,
            },
          });
          break;
        case "doesNotContain":
          data.push({
            NOT: {
              data: {
                path: [key],
                string_contains: val.value,
              },
            },
          });
          break;
        case "startsWith":
          data.push({
            data: {
              path: [key],
              string_starts_with: val.value,
            },
          });
          break;
        case "doesNotStartWith":
          data.push({
            NOT: {
              data: {
                path: [key],
                string_starts_with: val.value,
              },
            },
          });
          break;
        case "endsWith":
          data.push({
            data: {
              path: [key],
              string_ends_with: val.value,
            },
          });
          break;
        case "doesNotEndWith":
          data.push({
            NOT: {
              data: {
                path: [key],
                string_ends_with: val.value,
              },
            },
          });
          break;
      }
    });

    whereClause.push({
      AND: data,
    });
  }

  if (filterCriteria?.responseIds) {
    whereClause.push({
      id: { in: filterCriteria.responseIds },
    });
  }

  if (filterCriteria?.quotas) {
    const quotaFilters: Prisma.ResponseWhereInput[] = [];

    Object.entries(filterCriteria.quotas).forEach(([quotaId, { op }]) => {
      if (op === "screenedOutNotInQuota") {
        quotaFilters.push({
          NOT: {
            quotaLinks: {
              some: {
                quotaId,
              },
            },
          },
        });
      } else {
        quotaFilters.push({
          quotaLinks: {
            some: {
              quotaId,
              status: op,
            },
          },
        });
      }
    });

    if (quotaFilters.length > 0) {
      whereClause.push({
        AND: quotaFilters,
      });
    }
  }

  return { AND: whereClause };
};
