import type { TFunction } from "i18next";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { createContext, runInContext } from "node:vm";
import { describe, expect, test } from "vitest";
import { HUB_EMOTION_VALUES, HUB_SENTIMENT_VALUES } from "@formbricks/types/feedback-source";
import {
  EMOTION_MEASURE_ORDER,
  FEEDBACK_FIELDS,
  MEASURE_GROUP_ORDER,
  SELECTABLE_VALUE_DIMENSION_IDS,
  SENTIMENT_MEASURE_ORDER,
  VALUE_BAND_VALUES,
  formatCubeColumnHeader,
  getFieldById,
  getFilterOperatorsForType,
  getMeasureAxisDomain,
  getMeasureAxisLabel,
  getResponseBaseFamily,
  getResponseBaseMeasureId,
  getSentimentValueForMeasureId,
  getTranslatedDimensionValueLabel,
  getTranslatedFieldDescription,
  getTranslatedFieldLabel,
  isEnrichmentDimensionId,
  isNotEnrichedDimensionValue,
  isRatioMeasure,
  isSelectableValueDimension,
  sortMeasureIdsForCategoryAxis,
  sortRowsByEnumDimension,
} from "./schema-definition";

const chartCubeSchemaPath = fileURLToPath(
  new URL("../../../../../../charts/formbricks/cube/schema/FeedbackRecords.js", import.meta.url)
);
const dockerCubeSchemaPath = fileURLToPath(
  new URL("../../../../../../docker/cube/schema/FeedbackRecords.js", import.meta.url)
);

const readChartCubeSchema = (): string => readFileSync(chartCubeSchemaPath, "utf8");
const readDockerCubeSchema = (): string => readFileSync(dockerCubeSchemaPath, "utf8");
const getCubeMemberName = (id: string): string => id.replace("FeedbackRecords.", "");

interface CubeMember {
  sql?: string;
  description?: string;
  filters?: { sql: string }[];
  public?: boolean;
}
interface CubeDefinition {
  dimensions: Record<string, CubeMember>;
  measures: Record<string, CubeMember>;
}

/**
 * Runs a deployed Cube schema file for real and hands back the model it defines, with `${CUBE}`
 * resolved to the table alias `TBL`. Reading the evaluated model rather than the file text is what
 * keeps these assertions honest: a member added or renamed later cannot sidestep them.
 */
const evaluateCubeSchema = (path: string): CubeDefinition => {
  let captured: CubeDefinition | undefined;
  // The model is compiled per dataset inside `asyncModule` (ENG-6893) and joins the AnswerFilterN
  // aliases (ENG-6894); it is evaluated here for a dataset without embedded-data keys.
  process.env.CUBEJS_API_SECRET = process.env.CUBEJS_API_SECRET || "cube-secret";
  const cubeConfig = createRequire(import.meta.url)(
    path.replace(/schema\/FeedbackRecords\.js$/, "cube.js")
  ) as { ANSWER_FILTER_ALIAS_COUNT: number };
  const sandbox: Record<string, unknown> = {
    CUBE: "TBL",
    COMPILE_CONTEXT: { securityContext: {} },
    require: () => cubeConfig,
    asyncModule: (define: () => unknown) => {
      void define();
    },
    cube: (name: string, definition: CubeDefinition) => {
      if (name === "FeedbackRecords") captured = definition;
    },
  };
  for (let index = 1; index <= cubeConfig.ANSWER_FILTER_ALIAS_COUNT; index += 1) {
    sandbox[`AnswerFilter${index}`] = `AF${index}`;
  }
  createContext(sandbox);
  runInContext(readFileSync(path, "utf8"), sandbox);
  if (!captured) throw new Error(`No cube() definition found in ${path}`);
  return captured;
};

interface CubeRecord {
  fieldType: string;
  value: number | null;
}

const SQL_NUMBER = String.raw`-?\d+(?:\.\d+)?`;

/**
 * The small SQL dialect the bucket filters are written in: comparisons on `field_type` and
 * `value_number` joined by AND. `BETWEEN` is supported because the pre-fix predicates used it —
 * dropping it would make this pass against the very code it has to fail on.
 *
 * Ordering here is IEEE-754, not Postgres: `NaN >= 9` is false in JS but true in Postgres, which
 * sorts NaN above every other `numeric` / `double precision` value. So NaN buckets as a promoter
 * on the real database and as nothing here — the partition still holds on both sides, just in
 * different buckets. NaN is unreachable anyway (Zod's `z.number()` rejects NaN and ±Infinity, and
 * both ingest paths drop it), so do not "fix" this by adding NaN to the value lists: it would
 * report a gap that the database does not have.
 */
const SQL_CLAUSES: { pattern: RegExp; holds: (match: RegExpExecArray, record: CubeRecord) => boolean }[] = [
  {
    pattern: /^TBL\.field_type = '([a-z_]+)'/,
    holds: (match, record) => record.fieldType === match[1],
  },
  {
    pattern: /^TBL\.value_number IS NOT NULL/,
    holds: (_match, record) => record.value !== null,
  },
  {
    pattern: new RegExp(String.raw`^TBL\.value_number BETWEEN (${SQL_NUMBER}) AND (${SQL_NUMBER})`),
    holds: (match, record) =>
      record.value !== null && record.value >= Number(match[1]) && record.value <= Number(match[2]),
  },
  {
    pattern: new RegExp(String.raw`^TBL\.value_number (>=|<=|<>|>|<|=) (${SQL_NUMBER})`),
    holds: (match, record) => {
      // SQL three-valued logic: every comparison against NULL is UNKNOWN, never true.
      if (record.value === null) return false;
      const operand = Number(match[2]);
      switch (match[1]) {
        case ">=":
          return record.value >= operand;
        case "<=":
          return record.value <= operand;
        case ">":
          return record.value > operand;
        case "<":
          return record.value < operand;
        case "=":
          return record.value === operand;
        default:
          return record.value !== operand;
      }
    },
  },
];

/**
 * Evaluates one of those predicates against a single record. A clause it cannot read throws rather
 * than evaluating to false, so a predicate rewritten into an unsupported form fails the suite
 * loudly instead of quietly reporting an empty bucket.
 */
const evaluateSqlPredicate = (sql: string, record: CubeRecord): boolean => {
  let rest = sql.replace(/\s+/g, " ").trim();
  let result = true;

  while (rest.length > 0) {
    const clause = SQL_CLAUSES.map((candidate) => ({
      candidate,
      match: candidate.pattern.exec(rest),
    })).find((entry): entry is { candidate: (typeof SQL_CLAUSES)[number]; match: RegExpExecArray } =>
      Boolean(entry.match)
    );
    if (!clause) throw new Error(`Unsupported SQL clause in predicate: "${rest}"`);

    result = clause.candidate.holds(clause.match, record) && result;
    rest = rest.slice(clause.match[0].length).trim();
    if (rest.length === 0) break;
    if (!rest.startsWith("AND ")) throw new Error(`Unsupported SQL connective in predicate: "${rest}"`);
    rest = rest.slice("AND ".length).trim();
  }

  return result;
};

describe("schema-definition", () => {
  describe("getFilterOperatorsForType", () => {
    test("returns string operators", () => {
      const ops = getFilterOperatorsForType("string");
      expect(ops).toContain("equals");
      expect(ops).toContain("contains");
      expect(ops).toContain("set");
    });

    test("returns number operators", () => {
      const ops = getFilterOperatorsForType("number");
      expect(ops).toContain("gt");
      expect(ops).toContain("gte");
      expect(ops).toContain("lt");
      expect(ops).toContain("lte");
    });

    test("returns time operators", () => {
      const ops = getFilterOperatorsForType("time");
      expect(ops).toContain("equals");
      expect(ops).toContain("set");
    });
  });

  describe("getFieldById", () => {
    test("returns dimension by id", () => {
      const field = getFieldById("FeedbackRecords.sourceType");
      expect(field).toBeDefined();
      expect(field?.label).toBe("Source Type");
      expect(field?.type).toBe("string");
    });

    test("returns measure by id", () => {
      const field = getFieldById("FeedbackRecords.count");
      expect(field).toBeDefined();
      expect(field?.label).toBe("Feedback Records");
    });

    test("returns undefined for unknown id", () => {
      expect(getFieldById("Unknown.field")).toBeUndefined();
    });
  });

  describe("formatCubeColumnHeader", () => {
    test("extracts granularity label for time dimension key", () => {
      expect(formatCubeColumnHeader("FeedbackRecords.collectedAt.day")).toBe("Day");
      expect(formatCubeColumnHeader("FeedbackRecords.collectedAt.month")).toBe("Month");
    });

    test("returns field label for known dimension/measure", () => {
      expect(formatCubeColumnHeader("FeedbackRecords.sourceType")).toBe("Source Type");
      expect(formatCubeColumnHeader("FeedbackRecords.count")).toBe("Feedback Records");
    });

    test("converts last segment to title case for unknown keys", () => {
      expect(formatCubeColumnHeader("Some.camelCaseKey")).toBe("Camel Case Key");
    });

    test("handles key with no dots", () => {
      expect(formatCubeColumnHeader("singleKey")).toBe("Single Key");
    });

    test("heads an embedded-data member with its key's own name when the server named it", () => {
      const plan = "FeedbackRecords.ed_plan_64879f7d";
      expect(formatCubeColumnHeader(plan, undefined, { [plan]: "Plan (EU)" })).toBe("Plan (EU)");
      // Other keys are untouched by the map.
      expect(formatCubeColumnHeader("FeedbackRecords.count", undefined, { [plan]: "Plan" })).toBe(
        "Feedback Records"
      );
    });
  });

  describe("FEEDBACK_FIELDS", () => {
    test("keeps the embedded-key discovery member queryable in both Cube deployments", () => {
      for (const path of [chartCubeSchemaPath, dockerCubeSchemaPath]) {
        expect(evaluateCubeSchema(path).dimensions.embeddedDataKey.public).toBe(true);
      }
    });

    test("exposes CSAT, CES, NPS, rating and universal measures", () => {
      const ids = FEEDBACK_FIELDS.measures.map((m) => m.id);
      expect(ids).toEqual(
        expect.arrayContaining([
          "FeedbackRecords.count",
          "FeedbackRecords.uniqueRespondents",
          "FeedbackRecords.uniqueResponses",
          "FeedbackRecords.npsScore",
          "FeedbackRecords.npsAverage",
          "FeedbackRecords.csatScore",
          "FeedbackRecords.csatAverage",
          "FeedbackRecords.csatSatisfiedCount",
          "FeedbackRecords.csatCount",
          "FeedbackRecords.cesAverage",
          "FeedbackRecords.cesCount",
          "FeedbackRecords.ratingAverage",
          "FeedbackRecords.ratingCount",
        ])
      );
      expect(ids).not.toContain("FeedbackRecords.averageScore");
    });

    test("every measure has a valid UX group", () => {
      for (const m of FEEDBACK_FIELDS.measures) {
        expect(MEASURE_GROUP_ORDER).toContain(m.group);
      }
    });

    test("labels buckets with the 'Domain: Detail' scheme", () => {
      // `group` only exists on measures, so look the ids up in the measures list directly.
      const getMeasureById = (id: string) => FEEDBACK_FIELDS.measures.find((m) => m.id === id);

      expect(getFieldById("FeedbackRecords.joyCount")?.label).toBe("Emotion: Joy");
      expect(getFieldById("FeedbackRecords.veryPositiveCount")?.label).toBe("Sentiment: Very positive");
      expect(getFieldById("FeedbackRecords.promoterCount")?.label).toBe("NPS: Promoters");
      expect(getMeasureById("FeedbackRecords.promoterCount")?.group).toBe("count");
      expect(getMeasureById("FeedbackRecords.npsAverage")?.group).toBe("average");
      expect(getMeasureById("FeedbackRecords.npsScore")?.group).toBe("score");
    });

    test("classifies scores and averages as ratios, and counts as additive", () => {
      // Drives two decisions that must not diverge: whether an empty bucket means 0 or "no value",
      // and whether per-group values may be folded into one.
      expect(isRatioMeasure("FeedbackRecords.npsScore")).toBe(true);
      expect(isRatioMeasure("FeedbackRecords.csatScore")).toBe(true);
      expect(isRatioMeasure("FeedbackRecords.npsAverage")).toBe(true);
      expect(isRatioMeasure("FeedbackRecords.sentimentAverage")).toBe(true);

      expect(isRatioMeasure("FeedbackRecords.count")).toBe(false);
      expect(isRatioMeasure("FeedbackRecords.promoterCount")).toBe(false);
      expect(isRatioMeasure("FeedbackRecords.uniqueRespondents")).toBe(false);

      // Not a measure, and not in the schema at all: both keep the additive default.
      expect(isRatioMeasure("FeedbackRecords.sourceName")).toBe(false);
      expect(isRatioMeasure("FeedbackRecords.notAMeasure")).toBe(false);
    });

    test("only exposes members present in the deployed Cube schema", () => {
      const chartCubeSchema = readChartCubeSchema();
      const exposedMembers = [...FEEDBACK_FIELDS.measures, ...FEEDBACK_FIELDS.dimensions].map(({ id }) =>
        getCubeMemberName(id)
      );

      for (const member of exposedMembers) {
        expect(chartCubeSchema).toContain(`    ${member}: {`);
      }
    });

    test("keeps the Helm and Docker Cube schemas in sync", () => {
      expect(readChartCubeSchema()).toBe(readDockerCubeSchema());
    });
  });

  describe("Response context (ENG-1555 metadata)", () => {
    const metadataDimensionIds = [
      "FeedbackRecords.metadataSource",
      "FeedbackRecords.metadataUrl",
      "FeedbackRecords.metadataBrowser",
      "FeedbackRecords.metadataOs",
      "FeedbackRecords.metadataDevice",
      "FeedbackRecords.metadataCountry",
      "FeedbackRecords.metadataAction",
      "FeedbackRecords.metadataFinished",
      "FeedbackRecords.metadataDurationSeconds",
      "FeedbackRecords.metadataEndingId",
      "FeedbackRecords.metadataSurveyType",
    ];

    test("exposes one dimension per key the ingestion allowlist writes", () => {
      const dimensionIds = FEEDBACK_FIELDS.dimensions.map((d) => d.id);
      expect(dimensionIds).toEqual(expect.arrayContaining(metadataDimensionIds));
    });

    test("types the two non-text keys as their own types rather than strings", () => {
      // The filter UI picks its operators off this type, so a boolean typed as a string would offer
      // `contains` on true/false and no gt/lt on the duration.
      expect(getFieldById("FeedbackRecords.metadataFinished")?.type).toBe("boolean");
      expect(getFieldById("FeedbackRecords.metadataDurationSeconds")?.type).toBe("number");
    });

    test("members exist in both deployed Cube schemas", () => {
      const dockerSchema = readDockerCubeSchema();
      const chartSchema = readChartCubeSchema();

      for (const id of metadataDimensionIds) {
        expect(dockerSchema).toContain(`    ${getCubeMemberName(id)}: {`);
        expect(chartSchema).toContain(`    ${getCubeMemberName(id)}: {`);
      }
    });

    test("reads the non-text keys through a guard instead of a bare cast", () => {
      // `metadata` is free-form jsonb any writer can fill, so a bare ::boolean / ::double precision
      // on a malformed value fails the whole chart query rather than that one row. The digit bounds
      // are part of the guard: an unbounded digit run still reads as a number but overflows or
      // underflows double precision, which raises 22003 for the whole query.
      for (const schema of [readDockerCubeSchema(), readChartCubeSchema()]) {
        expect(schema).toContain("LOWER(${CUBE}.metadata->>'finished') IN ('true', 'false')");
        expect(schema).toContain(
          "metadata->>'duration_seconds' ~ '\\\\A-?[0-9]{1,15}(\\\\.[0-9]{1,6})?\\\\Z'"
        );
      }
    });

    test("keeps every member's SQL free of JS replacement specials", () => {
      // Cube splices a member's SQL into its filter templates with String.prototype.replace, where
      // that SQL is the *replacement* argument — so `$'`, `` $` ``, `$&`, `$<name>`, `$1` and `$$`
      // are expansion tokens rather than literals there. A regex ending in `$'` is the easy way to
      // hit this: it swallowed the closing quote, spliced ` IS NULL` inside the string literal, and
      // turned `set` / `notSet` on metadataDurationSeconds into an HTTP 400. `$$` is the quiet one —
      // it collapses to a single `$` instead of erroring, so a dollar-quoted body would come out
      // subtly rewritten rather than rejected. Assert the class, not one pattern, and read it off
      // the evaluated model rather than the file text so a member added later cannot sidestep it.
      const REPLACEMENT_SPECIAL = /\$(['`&$]|<|\d)/;

      for (const path of [dockerCubeSchemaPath, chartCubeSchemaPath]) {
        const captured = evaluateCubeSchema(path);

        const members = [
          ...Object.entries(captured.dimensions ?? {}),
          ...Object.entries(captured.measures ?? {}),
        ];
        expect(members.length).toBeGreaterThan(0);

        const offenders = members
          .filter(
            ([, definition]) => typeof definition.sql === "string" && REPLACEMENT_SPECIAL.test(definition.sql)
          )
          .map(([name]) => name);
        expect(offenders).toEqual([]);
      }
    });

    test("offers a value pick-list for the low-cardinality keys only", () => {
      for (const id of [
        "FeedbackRecords.metadataSource",
        "FeedbackRecords.metadataSurveyType",
        "FeedbackRecords.metadataBrowser",
        "FeedbackRecords.metadataOs",
        "FeedbackRecords.metadataDevice",
        "FeedbackRecords.metadataCountry",
        "FeedbackRecords.metadataAction",
        "FeedbackRecords.metadataEndingId",
      ]) {
        expect(isSelectableValueDimension(id)).toBe(true);
      }
      // One bucket per path: a pick-list of URLs is the valueText problem again.
      expect(isSelectableValueDimension("FeedbackRecords.metadataUrl")).toBe(false);
    });

    test("labels resolve to i18n keys rather than the raw dimension id", () => {
      const t = ((key: string) => key) as unknown as TFunction;

      for (const id of metadataDimensionIds) {
        expect(getTranslatedFieldLabel(id, t)).toMatch(/^workspace\.analysis\.charts\.field_label_/);
      }
    });

    test("translates the descriptions that carry a chart-building caveat", () => {
      const t = ((key: string) => key) as unknown as TFunction;

      expect(getTranslatedFieldDescription("FeedbackRecords.metadataFinished", "fallback", t)).toBe(
        "workspace.analysis.charts.field_description_completed"
      );
      expect(getTranslatedFieldDescription("FeedbackRecords.metadataDurationSeconds", "fallback", t)).toBe(
        "workspace.analysis.charts.field_description_time_to_complete"
      );
    });
  });

  describe("Hub enrichment fields (sentiment + emotions)", () => {
    test("exposes the enrichment dimensions and measures", () => {
      const dimensionIds = FEEDBACK_FIELDS.dimensions.map((d) => d.id);
      expect(dimensionIds).toEqual(
        expect.arrayContaining([
          "FeedbackRecords.sentiment",
          "FeedbackRecords.sentimentScore",
          "FeedbackRecords.emotions",
        ])
      );

      const measureIds = FEEDBACK_FIELDS.measures.map((m) => m.id);
      expect(measureIds).toEqual(
        expect.arrayContaining([
          "FeedbackRecords.sentimentAverage",
          "FeedbackRecords.veryNegativeCount",
          "FeedbackRecords.negativeCount",
          "FeedbackRecords.neutralCount",
          "FeedbackRecords.positiveCount",
          "FeedbackRecords.veryPositiveCount",
          "FeedbackRecords.mixedCount",
          "FeedbackRecords.joyCount",
          "FeedbackRecords.angerCount",
          "FeedbackRecords.sadnessCount",
          "FeedbackRecords.fearCount",
          "FeedbackRecords.surpriseCount",
          "FeedbackRecords.disgustCount",
        ])
      );
    });

    test("orders sentiment count measures most-positive → mixed", () => {
      const expectedOrder = [
        "FeedbackRecords.veryPositiveCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.neutralCount",
        "FeedbackRecords.negativeCount",
        "FeedbackRecords.veryNegativeCount",
        "FeedbackRecords.mixedCount",
      ];
      const measureIds = FEEDBACK_FIELDS.measures.map((m) => m.id);
      const sentimentCountIds = measureIds.filter((id) => expectedOrder.includes(id));
      expect(sentimentCountIds).toEqual(expectedOrder);
    });

    test("orders emotion count measures by the fixed valence order", () => {
      const expectedOrder = [
        "FeedbackRecords.joyCount",
        "FeedbackRecords.surpriseCount",
        "FeedbackRecords.angerCount",
        "FeedbackRecords.sadnessCount",
        "FeedbackRecords.fearCount",
        "FeedbackRecords.disgustCount",
      ];
      const measureIds = FEEDBACK_FIELDS.measures.map((m) => m.id);
      expect(measureIds.filter((id) => expectedOrder.includes(id))).toEqual(expectedOrder);
    });

    test("measure display orders cover exactly their vocabularies", () => {
      expect([...EMOTION_MEASURE_ORDER].sort()).toEqual([...HUB_EMOTION_VALUES].sort());
      expect([...SENTIMENT_MEASURE_ORDER].sort()).toEqual([...HUB_SENTIMENT_VALUES].sort());
    });

    test("maps each sentiment count measure id back to its enum value", () => {
      expect(getSentimentValueForMeasureId("FeedbackRecords.veryNegativeCount")).toBe("very_negative");
      expect(getSentimentValueForMeasureId("FeedbackRecords.negativeCount")).toBe("negative");
      expect(getSentimentValueForMeasureId("FeedbackRecords.neutralCount")).toBe("neutral");
      expect(getSentimentValueForMeasureId("FeedbackRecords.positiveCount")).toBe("positive");
      expect(getSentimentValueForMeasureId("FeedbackRecords.veryPositiveCount")).toBe("very_positive");
      expect(getSentimentValueForMeasureId("FeedbackRecords.mixedCount")).toBe("mixed");
      // non-sentiment measures resolve to nothing
      expect(getSentimentValueForMeasureId("FeedbackRecords.count")).toBeUndefined();
      expect(getSentimentValueForMeasureId("FeedbackRecords.joyCount")).toBeUndefined();
    });

    test("labels each sentiment count measure (no raw-id fallback)", () => {
      const t = ((key: string) => key) as TFunction;
      const sentimentCountIds = [
        "FeedbackRecords.veryNegativeCount",
        "FeedbackRecords.negativeCount",
        "FeedbackRecords.neutralCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.veryPositiveCount",
        "FeedbackRecords.mixedCount",
      ];
      for (const id of sentimentCountIds) {
        // resolves to an i18n key, not the raw dimension id
        expect(getTranslatedFieldLabel(id, t)).toMatch(/^workspace\.analysis\.charts\.field_label_/);
        expect(getTranslatedFieldLabel(id, t)).not.toBe(id);
      }
    });

    test("enrichment members exist in both deployed Cube schemas", () => {
      const dockerSchema = readDockerCubeSchema();
      const chartSchema = readChartCubeSchema();
      const members = [
        "sentiment",
        "sentimentScore",
        "emotions",
        "sentimentAverage",
        "veryNegativeCount",
        "negativeCount",
        "neutralCount",
        "positiveCount",
        "veryPositiveCount",
        "mixedCount",
        "joyCount",
        "angerCount",
        "sadnessCount",
        "fearCount",
        "surpriseCount",
        "disgustCount",
      ];

      for (const member of members) {
        expect(dockerSchema).toContain(`    ${member}: {`);
        expect(chartSchema).toContain(`    ${member}: {`);
      }
    });
  });

  describe("getTranslatedFieldDescription", () => {
    // Returns something distinguishable from the key, so an assertion cannot pass on an id that
    // resolves to the *wrong* `field_description_*` key — which a key-echoing `t` would allow.
    const t = ((key: string) => `translated:${key}`) as TFunction;

    // The descriptions these ids carry are the copy that tells a user which of three
    // near-identical measures to pick. Routing them through `t()` is what puts them in front of a
    // non-English user; nothing else fails if a key is dropped from the map, because the fallback
    // silently serves the hardcoded English from FEEDBACK_FIELDS and `pnpm i18n` still passes.
    test.each([
      ["FeedbackRecords.valueId", "workspace.analysis.charts.field_description_value_option"],
      ["FeedbackRecords.valueText", "workspace.analysis.charts.field_description_value_text"],
      ["FeedbackRecords.count", "workspace.analysis.charts.field_description_count"],
      ["FeedbackRecords.uniqueRespondents", "workspace.analysis.charts.field_description_unique_respondents"],
      ["FeedbackRecords.uniqueResponses", "workspace.analysis.charts.field_description_unique_responses"],
    ])("resolves %s through i18n rather than the English fallback", (id, key) => {
      expect(getTranslatedFieldDescription(id, "english fallback", t)).toBe(`translated:${key}`);
    });

    test("falls back to the schema's own description for a member with no key", () => {
      expect(getTranslatedFieldDescription("FeedbackRecords.sourceType", "english fallback", t)).toBe(
        "english fallback"
      );
    });

    test("passes an absent description through rather than inventing one", () => {
      expect(getTranslatedFieldDescription("FeedbackRecords.sourceType", undefined, t)).toBeUndefined();
    });

    // The lookup is an object literal, so an id that collides with a prototype member must not
    // resolve through the prototype chain — the defect #8985 had to convert its own lookup to a Map
    // for. Unreachable today (every call site passes an id from the hardcoded FEEDBACK_FIELDS), so
    // this pins it rather than fixing something live.
    test("does not resolve an inherited property as a description", () => {
      expect(getTranslatedFieldDescription("constructor", "english fallback", t)).toBe("english fallback");
      expect(getTranslatedFieldDescription("toString", undefined, t)).toBeUndefined();
    });
  });

  describe("getTranslatedDimensionValueLabel", () => {
    const t = ((key: string) => key) as TFunction;

    test("maps sentiment tokens to their i18n keys", () => {
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sentiment", "very_negative", t)).toBe(
        "workspace.analysis.charts.sentiment_value_very_negative"
      );
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sentiment", "mixed", t)).toBe(
        "workspace.analysis.charts.sentiment_value_mixed"
      );
    });

    test("labels every Hub sentiment and emotion value the v3 filters accept", () => {
      for (const value of HUB_SENTIMENT_VALUES) {
        expect(getTranslatedDimensionValueLabel("FeedbackRecords.sentiment", value, t)).toBe(
          `workspace.analysis.charts.sentiment_value_${value}`
        );
      }
      for (const value of HUB_EMOTION_VALUES) {
        expect(getTranslatedDimensionValueLabel("FeedbackRecords.emotions", value, t)).toBe(
          `workspace.analysis.charts.emotion_value_${value}`
        );
      }
    });

    test("translates each token of a comma-separated emotions set", () => {
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.emotions", "anger, joy", t)).toBe(
        "workspace.analysis.charts.emotion_value_anger, workspace.analysis.charts.emotion_value_joy"
      );
    });

    test("returns undefined for unknown tokens and non-enum dimensions", () => {
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sentiment", "great", t)).toBeUndefined();
      expect(
        getTranslatedDimensionValueLabel("FeedbackRecords.emotions", "anger, ecstasy", t)
      ).toBeUndefined();
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sourceName", "anger", t)).toBeUndefined();
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sentiment", 3, t)).toBeUndefined();
    });

    test("labels empty enrichment values as 'Not enriched'", () => {
      for (const dimension of ["FeedbackRecords.sentiment", "FeedbackRecords.emotions"]) {
        for (const value of ["", "   ", null, undefined]) {
          expect(getTranslatedDimensionValueLabel(dimension, value, t)).toBe(
            "workspace.analysis.charts.not_enriched"
          );
        }
      }
    });

    test("maps every value band token to its i18n key, and nothing else", () => {
      for (const band of VALUE_BAND_VALUES) {
        expect(getTranslatedDimensionValueLabel("FeedbackRecords.valueBand", band, t)).toBe(
          `workspace.analysis.charts.value_band_${band}`
        );
      }
      expect(
        getTranslatedDimensionValueLabel("FeedbackRecords.valueBand", "very_positive", t)
      ).toBeUndefined();
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.valueBand", "", t)).toBeUndefined();
    });

    test("does not label empty values on non-enrichment dimensions", () => {
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sourceName", "", t)).toBeUndefined();
      expect(getTranslatedDimensionValueLabel("FeedbackRecords.sourceName", null, t)).toBeUndefined();
    });
  });

  describe("sortMeasureIdsForCategoryAxis", () => {
    test("sorts sentiment count measures into the sentiment scale order", () => {
      const pickerOrder = [
        "FeedbackRecords.veryPositiveCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.neutralCount",
        "FeedbackRecords.negativeCount",
        "FeedbackRecords.veryNegativeCount",
        "FeedbackRecords.mixedCount",
      ];
      expect(sortMeasureIdsForCategoryAxis(pickerOrder)).toEqual([
        "FeedbackRecords.veryNegativeCount",
        "FeedbackRecords.negativeCount",
        "FeedbackRecords.neutralCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.veryPositiveCount",
        "FeedbackRecords.mixedCount",
      ]);
    });

    test("keeps non-sentiment measures in their relative order, after sentiment ones", () => {
      const ids = [
        "FeedbackRecords.joyCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.count",
        "FeedbackRecords.veryNegativeCount",
      ];
      expect(sortMeasureIdsForCategoryAxis(ids)).toEqual([
        "FeedbackRecords.veryNegativeCount",
        "FeedbackRecords.positiveCount",
        "FeedbackRecords.joyCount",
        "FeedbackRecords.count",
      ]);
    });

    test("does not mutate the input array", () => {
      const ids = ["FeedbackRecords.positiveCount", "FeedbackRecords.veryNegativeCount"];
      sortMeasureIdsForCategoryAxis(ids);
      expect(ids).toEqual(["FeedbackRecords.positiveCount", "FeedbackRecords.veryNegativeCount"]);
    });
  });

  describe("getMeasureAxisLabel", () => {
    const t = ((key: string) => key) as TFunction;

    test("labels sentiment count measures with their short value label", () => {
      expect(getMeasureAxisLabel("FeedbackRecords.veryPositiveCount", t)).toBe(
        "workspace.analysis.charts.sentiment_value_very_positive"
      );
      expect(getMeasureAxisLabel("FeedbackRecords.mixedCount", t)).toBe(
        "workspace.analysis.charts.sentiment_value_mixed"
      );
    });

    test("labels emotion count measures with their short value label", () => {
      expect(getMeasureAxisLabel("FeedbackRecords.joyCount", t)).toBe(
        "workspace.analysis.charts.emotion_value_joy"
      );
      expect(getMeasureAxisLabel("FeedbackRecords.disgustCount", t)).toBe(
        "workspace.analysis.charts.emotion_value_disgust"
      );
    });

    test("falls back to the full column header for other measures", () => {
      expect(getMeasureAxisLabel("FeedbackRecords.count", t)).toBe(
        "workspace.analysis.charts.field_label_count"
      );
      // promoterCount is an NPS measure, not a sentiment/emotion enum measure
      expect(getMeasureAxisLabel("FeedbackRecords.promoterCount", t)).toBe(
        "workspace.analysis.charts.field_label_promoter_count"
      );
      expect(getMeasureAxisLabel("Some.unknownKey", t)).toBe("Unknown Key");
    });
  });

  describe("isNotEnrichedDimensionValue", () => {
    test("true only for empty values on sentiment/emotions dimensions", () => {
      expect(isNotEnrichedDimensionValue("FeedbackRecords.sentiment", "")).toBe(true);
      expect(isNotEnrichedDimensionValue("FeedbackRecords.sentiment", null)).toBe(true);
      expect(isNotEnrichedDimensionValue("FeedbackRecords.emotions", "  ")).toBe(true);
      // populated enrichment value → enriched, not gray
      expect(isNotEnrichedDimensionValue("FeedbackRecords.sentiment", "positive")).toBe(false);
      // empty value on a non-enrichment dimension → not the "not enriched" bucket
      expect(isNotEnrichedDimensionValue("FeedbackRecords.sourceName", "")).toBe(false);
    });
  });

  describe("isEnrichmentDimensionId", () => {
    test("recognizes the sentiment and emotions dimensions only", () => {
      expect(isEnrichmentDimensionId("FeedbackRecords.sentiment")).toBe(true);
      expect(isEnrichmentDimensionId("FeedbackRecords.emotions")).toBe(true);
      expect(isEnrichmentDimensionId("FeedbackRecords.sentimentScore")).toBe(false);
      expect(isEnrichmentDimensionId("FeedbackRecords.sourceName")).toBe(false);
    });
  });

  describe("sortRowsByEnumDimension", () => {
    test("sorts sentiment rows on the scale with mixed last and unknowns at the end", () => {
      const rows = [
        { "FeedbackRecords.sentiment": "mixed" },
        { "FeedbackRecords.sentiment": "positive" },
        { "FeedbackRecords.sentiment": "surprising" },
        { "FeedbackRecords.sentiment": "very_negative" },
        { "FeedbackRecords.sentiment": "neutral" },
      ];

      const sorted = sortRowsByEnumDimension(rows, "FeedbackRecords.sentiment");

      expect(sorted.map((r) => r["FeedbackRecords.sentiment"])).toEqual([
        "very_negative",
        "neutral",
        "positive",
        "mixed",
        "surprising",
      ]);
      // input untouched
      expect(rows[0]["FeedbackRecords.sentiment"]).toBe("mixed");
    });

    test("sorts value band rows positive-first with unknowns at the end", () => {
      const rows = [
        { "FeedbackRecords.valueBand": "detractor" },
        { "FeedbackRecords.valueBand": "mystery" },
        { "FeedbackRecords.valueBand": "promoter" },
        { "FeedbackRecords.valueBand": "passive" },
      ];
      expect(
        sortRowsByEnumDimension(rows, "FeedbackRecords.valueBand").map((r) => r["FeedbackRecords.valueBand"])
      ).toEqual(["promoter", "passive", "detractor", "mystery"]);
    });

    test("leaves rows of other dimensions unchanged", () => {
      const rows = [{ "FeedbackRecords.sourceName": "b" }, { "FeedbackRecords.sourceName": "a" }];
      expect(sortRowsByEnumDimension(rows, "FeedbackRecords.sourceName")).toBe(rows);
    });
  });

  describe("isSelectableValueDimension", () => {
    test("accepts low-cardinality string dimensions", () => {
      expect(isSelectableValueDimension("FeedbackRecords.sourceName")).toBe(true);
      expect(isSelectableValueDimension("FeedbackRecords.sourceType")).toBe(true);
      expect(isSelectableValueDimension("FeedbackRecords.language")).toBe(true);
      expect(isSelectableValueDimension("FeedbackRecords.fieldLabel")).toBe(true);
      expect(isSelectableValueDimension("FeedbackRecords.sentiment")).toBe(true);
    });

    test("rejects free-text, numeric, time, and unknown fields", () => {
      expect(isSelectableValueDimension("FeedbackRecords.valueText")).toBe(false);
      // multi-label set — equals on a picked combination is a trap, filter via contains
      expect(isSelectableValueDimension("FeedbackRecords.emotions")).toBe(false);
      expect(isSelectableValueDimension("FeedbackRecords.valueNumber")).toBe(false);
      expect(isSelectableValueDimension("FeedbackRecords.collectedAt")).toBe(false);
      expect(isSelectableValueDimension("FeedbackRecords.userId")).toBe(false);
      expect(isSelectableValueDimension("Unknown.field")).toBe(false);
    });

    test("every selectable dimension is a defined string dimension", () => {
      for (const id of SELECTABLE_VALUE_DIMENSION_IDS) {
        const field = getFieldById(id);
        expect(field).toBeDefined();
        expect(field?.type).toBe("string");
      }
    });
  });

  describe("normalized companion dimensions", () => {
    // Hidden LOWER(TRIM(...)) companions selected by the Cube queryRewrite for
    // case-insensitive equals/notEquals. Must exist in the deployed schema.
    const normalizedMembers = [
      "sourceTypeNormalized",
      "sourceNameNormalized",
      "fieldTypeNormalized",
      "fieldLabelNormalized",
      "fieldGroupLabelNormalized",
      "languageNormalized",
      "valueTextNormalized",
      "metadataSourceNormalized",
      "metadataBrowserNormalized",
      "metadataOsNormalized",
      "metadataDeviceNormalized",
      "metadataCountryNormalized",
      "metadataActionNormalized",
    ];

    test("are present in both Cube schemas with a LOWER(TRIM(...)) sql and hidden", () => {
      const dockerSchema = readDockerCubeSchema();
      const chartSchema = readChartCubeSchema();

      for (const member of normalizedMembers) {
        expect(dockerSchema).toContain(`    ${member}: {`);
        expect(chartSchema).toContain(`    ${member}: {`);
      }
      expect(dockerSchema).toContain("LOWER(TRIM(source_name))");
      expect(dockerSchema).toContain("shown: false");
    });

    test("are not exposed as user-facing dimensions", () => {
      const exposedIds = FEEDBACK_FIELDS.dimensions.map((d) => d.id);
      for (const member of normalizedMembers) {
        expect(exposedIds).not.toContain(`FeedbackRecords.${member}`);
      }
    });
  });

  describe("value band, axis domain and response base registry (ENG-3331)", () => {
    test("registers valueBand as a selectable string dimension and npsCount as a count", () => {
      expect(getFieldById("FeedbackRecords.valueBand")?.type).toBe("string");
      expect(isSelectableValueDimension("FeedbackRecords.valueBand")).toBe(true);
      expect(FEEDBACK_FIELDS.measures.find((m) => m.id === "FeedbackRecords.npsCount")).toMatchObject({
        type: "count",
        group: "count",
      });
      const t = ((key: string) => key) as TFunction;
      expect(getTranslatedFieldLabel("FeedbackRecords.valueBand", t)).toBe(
        "workspace.analysis.charts.field_label_value_band"
      );
      expect(getTranslatedFieldLabel("FeedbackRecords.npsCount", t)).toBe(
        "workspace.analysis.charts.field_label_nps_count"
      );
    });

    test("pins only the two bounded scores to their full range", () => {
      expect(getMeasureAxisDomain("FeedbackRecords.npsScore")).toEqual([-100, 100]);
      expect(getMeasureAxisDomain("FeedbackRecords.csatScore")).toEqual([0, 100]);
      expect(getMeasureAxisDomain("FeedbackRecords.npsAverage")).toBeUndefined();
      expect(getMeasureAxisDomain("FeedbackRecords.count")).toBeUndefined();
    });

    test.each([
      [["FeedbackRecords.npsScore"], "FeedbackRecords.npsCount"],
      [
        ["FeedbackRecords.npsScore", "FeedbackRecords.npsAverage", "FeedbackRecords.promoterCount"],
        "FeedbackRecords.npsCount",
      ],
      [["FeedbackRecords.npsCount"], "FeedbackRecords.npsCount"],
      [["FeedbackRecords.csatScore", "FeedbackRecords.csatNeutralCount"], "FeedbackRecords.csatCount"],
      [["FeedbackRecords.cesAverage"], "FeedbackRecords.cesCount"],
      [["FeedbackRecords.ratingAverage"], "FeedbackRecords.ratingCount"],
    ])("%j has the response base %s", (measures, base) => {
      expect(getResponseBaseMeasureId(measures)).toBe(base);
    });

    test.each([
      ["NPS beside CSAT", ["FeedbackRecords.npsScore", "FeedbackRecords.csatScore"]],
      ["a score beside a generic count", ["FeedbackRecords.npsScore", "FeedbackRecords.count"]],
      ["a generic count", ["FeedbackRecords.count"]],
      ["sentiment", ["FeedbackRecords.sentimentAverage"]],
      ["no measures", []],
    ])("%s has no single response base", (_label, measures) => {
      expect(getResponseBaseMeasureId(measures)).toBeUndefined();
    });

    test("names the answer type of each response base", () => {
      expect(getResponseBaseFamily("FeedbackRecords.npsCount")).toBe("nps");
      expect(getResponseBaseFamily("FeedbackRecords.csatCount")).toBe("csat");
      expect(getResponseBaseFamily("FeedbackRecords.cesCount")).toBe("ces");
      expect(getResponseBaseFamily("FeedbackRecords.ratingCount")).toBe("rating");
      expect(getResponseBaseFamily("FeedbackRecords.count")).toBeUndefined();
    });

    test("every response base is itself a registered count measure", () => {
      for (const measure of FEEDBACK_FIELDS.measures) {
        if (!measure.responseBaseMeasureId) continue;
        const base = FEEDBACK_FIELDS.measures.find((m) => m.id === measure.responseBaseMeasureId);
        expect({ measure: measure.id, type: base?.type }).toEqual({ measure: measure.id, type: "count" });
      }
    });
  });

  describe("NPS and CSAT bucket predicates (ENG-3147)", () => {
    // `value_number` is an unbounded numeric — the API schema puts no integer or range bound on it,
    // and both ingest paths parse it with Number.parseFloat. So a bucket set that only covers the
    // integers of the documented scale leaves gaps, and a value in a gap still counts in the score's
    // denominator: two records of 6.5 and 8.5 produced "NPS Average 7.5" beside "NPS Score 0".
    // The buckets must therefore partition the whole number line, not just the scale.
    const NPS_BUCKETS = ["promoterCount", "passiveCount", "detractorCount"];
    const CSAT_BUCKETS = ["csatSatisfiedCount", "csatNeutralCount", "csatDissatisfiedCount"];

    // One table per scale: the boundary values and the one bucket each must land in. Both the
    // per-value cases and the score-denominator invariants below read their values from here, so
    // there is a single list to extend when a new boundary is worth covering.
    const NPS_BUCKET_CASES: [number, string][] = [
      [-1, "detractorCount"],
      [0, "detractorCount"],
      [6, "detractorCount"],
      [6.5, "detractorCount"],
      [7, "passiveCount"],
      [8, "passiveCount"],
      [8.5, "passiveCount"],
      [9, "promoterCount"],
      [10, "promoterCount"],
      [11, "promoterCount"],
    ];
    const CSAT_BUCKET_CASES: [number, string][] = [
      [0, "csatDissatisfiedCount"],
      [1, "csatDissatisfiedCount"],
      [2, "csatDissatisfiedCount"],
      [2.5, "csatDissatisfiedCount"],
      [3, "csatNeutralCount"],
      [3.5, "csatNeutralCount"],
      [4, "csatSatisfiedCount"],
      [5, "csatSatisfiedCount"],
      [6, "csatSatisfiedCount"],
    ];

    const NPS_VALUES = NPS_BUCKET_CASES.map(([value]) => value);
    const CSAT_VALUES = CSAT_BUCKET_CASES.map(([value]) => value);

    const bucketPredicate = (model: CubeDefinition, measure: string): string => {
      const filters = model.measures[measure]?.filters ?? [];
      expect(filters).toHaveLength(1);
      return filters[0].sql.replace(/\s+/g, " ").trim();
    };

    /** The `COUNT(CASE WHEN … THEN 1 END)` arms of a score measure, deduplicated. */
    const scoreArms = (model: CubeDefinition, measure: string): Set<string> => {
      const sql = model.measures[measure]?.sql ?? "";
      const arms = [...sql.matchAll(/COUNT\(CASE WHEN ([\s\S]+?) THEN 1 END\)/g)].map(([, arm]) =>
        arm.replace(/\s+/g, " ").trim()
      );
      expect(arms.length).toBeGreaterThan(0);
      return new Set(arms);
    };

    const matchingBuckets = (model: CubeDefinition, buckets: string[], record: CubeRecord): string[] =>
      buckets.filter((measure) => evaluateSqlPredicate(bucketPredicate(model, measure), record));

    /** The `WHEN … THEN '<token>'` arms of the valueBand CASE, keyed by the band token. */
    const bandArms = (model: CubeDefinition): Record<string, string> => {
      const sql = (model.dimensions.valueBand?.sql ?? "").replace(/\s+/g, " ");
      return Object.fromEntries(
        [...sql.matchAll(/WHEN (.+?) THEN '([a-z]+)'/g)].map(([, predicate, token]) => [
          token,
          predicate.trim(),
        ])
      );
    };

    /** The band the CASE assigns: the first arm that holds, as Postgres evaluates it. */
    const bandFor = (model: CubeDefinition, record: CubeRecord): string | null =>
      Object.entries(bandArms(model)).find(([, predicate]) => evaluateSqlPredicate(predicate, record))?.[0] ??
      null;

    const BAND_OF_BUCKET: Record<string, string> = {
      promoterCount: "promoter",
      passiveCount: "passive",
      detractorCount: "detractor",
      csatSatisfiedCount: "satisfied",
      csatNeutralCount: "neutral",
      csatDissatisfiedCount: "dissatisfied",
    };

    describe.each([
      ["docker", dockerCubeSchemaPath],
      ["helm chart", chartCubeSchemaPath],
    ])("%s cube schema", (_label, schemaPath) => {
      const model = evaluateCubeSchema(schemaPath);

      test.each(NPS_BUCKET_CASES)("an NPS value of %p falls in exactly one bucket", (value, expected) => {
        expect(matchingBuckets(model, NPS_BUCKETS, { fieldType: "nps", value })).toEqual([expected]);
      });

      test.each(CSAT_BUCKET_CASES)("a CSAT value of %p falls in exactly one bucket", (value, expected) => {
        expect(matchingBuckets(model, CSAT_BUCKETS, { fieldType: "csat", value })).toEqual([expected]);
      });

      test("no bucket claims a dismissed answer or another field type", () => {
        expect(matchingBuckets(model, NPS_BUCKETS, { fieldType: "nps", value: null })).toEqual([]);
        expect(matchingBuckets(model, CSAT_BUCKETS, { fieldType: "csat", value: null })).toEqual([]);
        // A CSAT 5 must not be counted as an NPS detractor, nor an NPS 2 as CSAT dissatisfied.
        expect(matchingBuckets(model, NPS_BUCKETS, { fieldType: "csat", value: 5 })).toEqual([]);
        expect(matchingBuckets(model, CSAT_BUCKETS, { fieldType: "nps", value: 2 })).toEqual([]);
      });

      test("everything npsScore divides by lands in exactly one NPS bucket", () => {
        // The defect this pins: the denominator counted every answered record while the numerator
        // arms covered only part of the line, so a gap value dragged the score toward 0.
        const denominator = [...scoreArms(model, "npsScore")].find((arm) => arm.includes("IS NOT NULL"));
        expect(denominator).toBeDefined();

        for (const value of NPS_VALUES) {
          const record: CubeRecord = { fieldType: "nps", value };
          expect({
            value,
            counted: evaluateSqlPredicate(denominator ?? "", record),
            buckets: matchingBuckets(model, NPS_BUCKETS, record).length,
          }).toEqual({ value, counted: true, buckets: 1 });
        }
      });

      test("everything csatScore divides by lands in exactly one CSAT bucket", () => {
        const denominator = [...scoreArms(model, "csatScore")].find((arm) => arm.includes("IS NOT NULL"));
        expect(denominator).toBeDefined();

        for (const value of CSAT_VALUES) {
          const record: CubeRecord = { fieldType: "csat", value };
          expect({
            value,
            counted: evaluateSqlPredicate(denominator ?? "", record),
            buckets: matchingBuckets(model, CSAT_BUCKETS, record).length,
          }).toEqual({ value, counted: true, buckets: 1 });
        }
      });

      test("npsScore counts the same promoters and detractors as the bucket measures", () => {
        // The partition above is proven on the `*Count` filters; the score has its predicates
        // written out a second time inline, and only this ties the two copies together.
        expect(scoreArms(model, "npsScore")).toEqual(
          new Set([
            bucketPredicate(model, "promoterCount"),
            bucketPredicate(model, "detractorCount"),
            "TBL.field_type = 'nps' AND TBL.value_number IS NOT NULL",
          ])
        );
      });

      test("valueBand assigns each band with the same predicate as its bucket measure (ENG-3331)", () => {
        // A band written out a second time could drift from its *Count measure, and a breakdown by
        // band would then disagree with the promoter/passive/detractor counts beside it.
        expect(bandArms(model)).toEqual(
          Object.fromEntries(
            Object.entries(BAND_OF_BUCKET).map(([bucket, band]) => [band, bucketPredicate(model, bucket)])
          )
        );
      });

      test.each([
        ...NPS_BUCKET_CASES.map(([value, bucket]) => ["nps", value, bucket] as const),
        ...CSAT_BUCKET_CASES.map(([value, bucket]) => ["csat", value, bucket] as const),
      ])("valueBand puts a %s value of %p in the band of %s", (fieldType, value, bucket) => {
        expect(bandFor(model, { fieldType, value })).toBe(BAND_OF_BUCKET[bucket]);
      });

      test("valueBand leaves unanswered records and other field types without a band", () => {
        expect(bandFor(model, { fieldType: "nps", value: null })).toBeNull();
        expect(bandFor(model, { fieldType: "csat", value: null })).toBeNull();
        expect(bandFor(model, { fieldType: "text", value: 9 })).toBeNull();
        expect(bandFor(model, { fieldType: "ces", value: 5 })).toBeNull();
      });

      test("npsCount counts exactly the records npsScore divides by", () => {
        expect(bucketPredicate(model, "npsCount")).toBe(
          "TBL.field_type = 'nps' AND TBL.value_number IS NOT NULL"
        );
        expect(scoreArms(model, "npsScore")).toContain(bucketPredicate(model, "npsCount"));
      });

      test("csatScore counts the same satisfied responses as the bucket measure", () => {
        expect(scoreArms(model, "csatScore")).toEqual(
          new Set([
            bucketPredicate(model, "csatSatisfiedCount"),
            "TBL.field_type = 'csat' AND TBL.value_number IS NOT NULL",
          ])
        );
      });

      // Each of these measures describes its own predicate, and that sentence is written twice —
      // once in the Cube schema, once as the chart picker's copy in FEEDBACK_FIELDS. Editing one
      // copy and not the other is how "score 0-6" survived a predicate that no longer said 0-6.
      // Scoped to the bucket and score measures on purpose: the rest of the two description sets
      // deliberately diverge, because the picker's copy is written for a chart builder (it says
      // "Value (Option)" and "empty") while the schema's is written for the SQL model ("valueId",
      // "NULL"). `toStartWith` rather than equality, because the two score measures append a
      // "NULL when there are no answered…" sentence that the picker has no room for.
      test.each([
        "npsScore",
        "npsCount",
        "promoterCount",
        "passiveCount",
        "detractorCount",
        "csatScore",
        "csatSatisfiedCount",
        "csatNeutralCount",
        "csatDissatisfiedCount",
      ])("%s describes the same bucket in the schema and the chart picker", (measure) => {
        const pickerDescription = FEEDBACK_FIELDS.measures.find(
          (m) => m.id === `FeedbackRecords.${measure}`
        )?.description;
        expect(pickerDescription).toBeTruthy();

        // Sliced rather than `startsWith` so a drifted string fails with a diff of the two copies.
        const schemaDescription = model.measures[measure]?.description ?? "";
        expect(schemaDescription.slice(0, (pickerDescription ?? "").length)).toBe(pickerDescription);
      });
    });

    describe("the SQL predicate translator those assertions rest on", () => {
      test("reads the comparison forms the schema uses, the pre-fix BETWEEN included", () => {
        const between = "TBL.field_type = 'nps' AND TBL.value_number BETWEEN 7 AND 8";
        expect(evaluateSqlPredicate(between, { fieldType: "nps", value: 7 })).toBe(true);
        expect(evaluateSqlPredicate(between, { fieldType: "nps", value: 6.5 })).toBe(false);
        expect(evaluateSqlPredicate(between, { fieldType: "csat", value: 7 })).toBe(false);

        const halfOpen = "TBL.value_number >= 7 AND TBL.value_number < 9";
        expect(evaluateSqlPredicate(halfOpen, { fieldType: "nps", value: 8.5 })).toBe(true);
        expect(evaluateSqlPredicate(halfOpen, { fieldType: "nps", value: 9 })).toBe(false);

        expect(evaluateSqlPredicate("TBL.value_number = 3", { fieldType: "csat", value: 3.5 })).toBe(false);
        expect(evaluateSqlPredicate("TBL.value_number < 3", { fieldType: "csat", value: null })).toBe(false);
        expect(evaluateSqlPredicate("TBL.value_number IS NOT NULL", { fieldType: "csat", value: null })).toBe(
          false
        );
      });

      test("throws on a clause it cannot read rather than reporting an empty bucket", () => {
        expect(() =>
          evaluateSqlPredicate("TBL.value_number IN (1, 2)", { fieldType: "nps", value: 1 })
        ).toThrow(/Unsupported SQL clause/);
        expect(() =>
          evaluateSqlPredicate("TBL.value_number >= 7 OR TBL.value_number < 3", {
            fieldType: "nps",
            value: 1,
          })
        ).toThrow(/Unsupported SQL connective/);
      });
    });
  });
});
