import { describe, expect, test } from "vitest";
import { z } from "zod";
import { CANONICAL_LANGUAGE_CODES } from "@formbricks/i18n-utils/canonical";
import { validateElementLabels } from "@formbricks/types/surveys/elements-validation";
import { findArrayBudgetViolation } from "@/app/api/v3/lib/array-budget";
import { V3_INVALID_PARAMS_MAX, V3_INVALID_PARAM_REASON_MAX_CHARS } from "@/app/api/v3/lib/invalid-params";
import {
  V3_SURVEY_BLOCK_OPS_MAX,
  V3_SURVEY_BLOCK_ORDER_MAX,
  V3_SURVEY_MAX_BLOCKS,
  V3_SURVEY_MAX_DOCUMENT_LOCALE_KEYS,
  V3_SURVEY_MAX_EMBEDDED_FIELDS,
  V3_SURVEY_MAX_ENDINGS,
  V3_SURVEY_MAX_HIDDEN_FIELDS,
  V3_SURVEY_MAX_LANGUAGES,
  V3_SURVEY_MAX_START_LOGIC_RULES,
  V3_SURVEY_MAX_TRANSLATIONS,
  V3_SURVEY_MAX_TRIGGERS,
  V3_SURVEY_MAX_VARIABLES,
  ZV3CreateSurveyBody,
  ZV3CreateSurveyQuery,
  ZV3EditSurveyBlocksBody,
  ZV3PatchSurveyBody,
  ZV3SetSurveyBlockOrderBody,
  createZV3PatchSurveyBodySchema,
  formatV3ZodInvalidParams,
} from "./schemas";

const validCreateBody = {
  workspaceId: "clxx1234567890123456789012",
  name: "Product Feedback",
  blocks: [
    {
      id: "clbk1234567890123456789012",
      name: "Main Block",
      elements: [
        {
          id: "satisfaction",
          type: "openText",
          headline: { "en-US": "What should we improve?" },
          required: true,
        },
      ],
    },
  ],
};

describe("ZV3CreateSurveyBody", () => {
  test("accepts a valid block-based create body and applies public defaults", () => {
    const parsed = ZV3CreateSurveyBody.parse(validCreateBody);

    expect(parsed).toMatchObject({
      workspaceId: validCreateBody.workspaceId,
      name: "Product Feedback",
      type: "link",
      status: "draft",
      metadata: {},
      defaultLanguage: "en-US",
      languages: [],
      showLanguageSwitch: null,
      autoSelectLanguage: null,
      welcomeCard: { enabled: false },
      endings: [],
      hiddenFields: { enabled: false },
      variables: [],
    });
    expect(parsed.blocks[0].elements[0]).toMatchObject({
      headline: { default: "What should we improve?" },
    });
  });

  test("generates server-managed block and variable ids on create when omitted", () => {
    const parsed = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      blocks: [
        {
          name: "Generated ID Block",
          elements: validCreateBody.blocks[0].elements,
        },
      ],
      variables: [
        {
          name: "score",
          type: "number",
          value: 0,
        },
      ],
    });

    expect(parsed.blocks[0].id).toEqual(expect.any(String));
    expect(parsed.blocks[0].id.length).toBeGreaterThan(0);
    expect(parsed.variables[0].id).toEqual(expect.any(String));
    expect(parsed.variables[0].id.length).toBeGreaterThan(0);
  });

  test("normalizes locale maps and language codes before shared survey validation", () => {
    const parsed = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      defaultLanguage: "en_us",
      languages: [{ code: "de_de" }],
      welcomeCard: {
        enabled: true,
        headline: { en_us: "Welcome", de_de: "Willkommen" },
      },
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              headline: { en_us: "Hello", de_de: "Hallo" },
            },
          ],
        },
      ],
    });

    expect(parsed.defaultLanguage).toBe("en-US");
    expect(parsed.languages).toEqual([{ code: "de-DE", enabled: true }]);
    expect(parsed.welcomeCard).toMatchObject({
      headline: { default: "Welcome", "de-DE": "Willkommen" },
    });
    expect(parsed.blocks[0].elements[0]).toMatchObject({
      headline: { default: "Hello", "de-DE": "Hallo" },
    });
  });

  test("rejects an invalid defaultLanguage instead of silently defaulting", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      defaultLanguage: "not a locale",
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "defaultLanguage",
            reason: "Language 'not a locale' is not a valid locale code",
            code: "invalid_locale",
          }),
        ])
      );
    }
  });

  test("rejects duplicate locale keys after normalization", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              headline: { "en-US": "Hello", en_us: "Duplicate" },
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "blocks.0.elements.0.headline.en_us",
            reason: "Language key 'en_us' duplicates 'en-US' after locale normalization",
            code: "duplicate_locale",
          }),
        ])
      );
    }
  });

  test("accepts the language settings on create", () => {
    const parsed = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      showLanguageSwitch: true,
      autoSelectLanguage: true,
    });

    expect(parsed).toMatchObject({ showLanguageSwitch: true, autoSelectLanguage: true });
    expect(ZV3CreateSurveyBody.safeParse({ ...validCreateBody, autoSelectLanguage: 1 }).success).toBe(false);
  });

  test("rejects unsupported top-level fields instead of silently ignoring them", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      questions: [],
      styling: {},
      createdBy: "user_1",
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
      expect.arrayContaining(["questions", "styling", "createdBy"])
    );
  });

  test("rejects unsupported nested fields instead of stripping them", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          targeting: {},
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              analytics: {},
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
      expect.arrayContaining(["blocks.0.targeting", "blocks.0.elements.0.analytics"])
    );
  });

  test("accepts a signature element and defaults allowTypedSignature to true", () => {
    const body = (extra: Record<string, unknown> = {}) => ({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            { id: "sign", type: "signature", headline: { "en-US": "Sign here" }, required: true, ...extra },
          ],
        },
      ],
    });

    const parsed = ZV3CreateSurveyBody.parse(body());
    expect(parsed.blocks[0].elements[0]).toMatchObject({ type: "signature", allowTypedSignature: true });

    const withoutTyping = ZV3CreateSurveyBody.parse(body({ allowTypedSignature: false }));
    expect(withoutTyping.blocks[0].elements[0]).toMatchObject({ allowTypedSignature: false });
  });

  test("rejects allowTypedSignature on an element that is not a signature, and file fields on a signature", () => {
    const withElement = (element: Record<string, unknown>) => ({
      ...validCreateBody,
      blocks: [{ ...validCreateBody.blocks[0], elements: [element] }],
    });

    const onText = ZV3CreateSurveyBody.safeParse(
      withElement({ ...validCreateBody.blocks[0].elements[0], allowTypedSignature: true })
    );
    expect(onText.success).toBe(false);
    expect(onText.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.elements.0.allowTypedSignature"
    );

    const fileFieldsOnSignature = ZV3CreateSurveyBody.safeParse(
      withElement({
        id: "sign",
        type: "signature",
        headline: { "en-US": "Sign here" },
        required: true,
        allowedFileExtensions: ["pdf"],
        maxSizeInMB: 5,
      })
    );
    expect(fileFieldsOnSignature.success).toBe(false);
    expect(fileFieldsOnSignature.error?.issues.map((issue) => issue.path.join("."))).toEqual(
      expect.arrayContaining(["blocks.0.elements.0.allowedFileExtensions", "blocks.0.elements.0.maxSizeInMB"])
    );
  });

  test("rejects element fields that do not belong to the selected element type", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              buttonUrl: "https://example.com",
              scale: "star",
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.elements.0.buttonUrl"
    );
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain("blocks.0.elements.0.scale");
    expect(
      result.error?.issues.find((issue) => issue.path.join(".") === "blocks.0.elements.0.buttonUrl")
    ).toMatchObject({
      message: expect.stringContaining("element type 'openText'"),
    });
  });

  // Regression (ENG-2411): `buttonUrl` used to be validated with `z.url()`, which accepts any value
  // `new URL()` parses — `javascript:` included — so a script-capable scheme reached the renderer, where
  // it is handed to `window.open()`.
  const ctaCreateBody = (buttonUrl: string) => ({
    ...validCreateBody,
    blocks: [
      {
        ...validCreateBody.blocks[0],
        elements: [
          {
            id: "cta",
            type: "cta",
            headline: { "en-US": "Read the docs" },
            required: false,
            buttonExternal: true,
            ctaButtonLabel: { "en-US": "Open" },
            buttonUrl,
          },
        ],
      },
    ],
  });

  test.each([
    "javascript:alert(document.domain)",
    "JavaScript:alert(1)",
    "java\tscript:alert(1)",
    "data:text/html,<script>alert(1)</script>",
    "vbscript:msgbox(1)",
  ])("rejects a cta buttonUrl with the script-capable scheme %j", (buttonUrl) => {
    const result = ZV3CreateSurveyBody.safeParse(ctaCreateBody(buttonUrl));

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.elements.0.buttonUrl"
    );
  });

  test.each(["https://formbricks.com/docs", "http://localhost:3000/docs", "mailto:support@example.com"])(
    "accepts a cta buttonUrl with the safe scheme %j",
    (buttonUrl) => {
      expect(ZV3CreateSurveyBody.safeParse(ctaCreateBody(buttonUrl)).success).toBe(true);
    }
  );

  test("rejects choice fields that do not belong to the selected element type", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              id: "choices",
              type: "multipleChoiceSingle",
              headline: { "en-US": "Pick one" },
              required: true,
              choices: [
                { id: "choice_1", label: { "en-US": "A" }, imageUrl: "https://example.com/a.png" },
                { id: "choice_2", label: { "en-US": "B" } },
              ],
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.elements.0.choices.0.imageUrl"
    );
    expect(
      result.error?.issues.find((issue) => issue.path.join(".") === "blocks.0.elements.0.choices.0.imageUrl")
    ).toMatchObject({
      message: expect.stringContaining("Allowed fields: code, hidden, id, label, showIf"),
    });
  });

  test("does not rewrite locale-shaped objects in logic metadata", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
            },
          ],
          logic: [
            {
              id: "cllog123456789012345678901",
              conditions: {
                id: "clgrp123456789012345678901",
                connector: "and",
                conditions: [
                  {
                    id: "clcon123456789012345678901",
                    leftOperand: {
                      type: "element",
                      value: "satisfaction",
                      meta: { "en-US": "metadata" },
                    },
                    operator: "isSubmitted",
                  },
                ],
              },
              actions: [
                {
                  id: "clact123456789012345678901",
                  objective: "requireAnswer",
                  target: "satisfaction",
                },
              ],
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(true);
    if (!result.success) {
      throw new Error("Expected schema validation to pass");
    }
    expect(result.data.blocks[0].logic?.[0].conditions.conditions[0]).toMatchObject({
      leftOperand: {
        meta: { "en-US": "metadata" },
      },
    });
  });

  test("accepts show-if on blocks and elements, and rejects unknown keys inside it (ENG-6931)", () => {
    const showIf = {
      id: "clshowifgroup00000000001",
      connector: "and",
      conditions: [
        {
          id: "clshowifcond000000000001",
          leftOperand: { type: "hiddenField", value: "plan" },
          operator: "isSet",
        },
      ],
    };
    const withShowIf = (condition: Record<string, unknown>) => ({
      ...validCreateBody,
      hiddenFields: { enabled: true, fieldIds: ["plan"] },
      blocks: [
        {
          ...validCreateBody.blocks[0],
          showIf: { ...showIf, conditions: [condition] },
          elements: [{ ...validCreateBody.blocks[0].elements[0], showIf }],
        },
      ],
    });

    const accepted = ZV3CreateSurveyBody.safeParse(withShowIf(showIf.conditions[0]));
    expect(accepted.error?.issues ?? []).toEqual([]);
    expect(accepted.data?.blocks[0].showIf).toEqual(showIf);
    expect(accepted.data?.blocks[0].elements[0].showIf).toEqual(showIf);

    const rejected = ZV3CreateSurveyBody.safeParse(withShowIf({ ...showIf.conditions[0], note: "x" }));
    expect(rejected.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.showIf.conditions.0.note"
    );
  });

  test("accepts show-if and hidden on choices, picture choices and matrix rows and columns (ENG-6937)", () => {
    const showIf = {
      id: "clshowifgroup00000000001",
      connector: "and",
      conditions: [
        {
          id: "clshowifcond000000000001",
          leftOperand: { type: "hiddenField", value: "plan" },
          operator: "isSet",
        },
      ],
    };
    const option = (id: string, extra: Record<string, unknown> = {}) => ({
      id,
      label: { "en-US": id },
      ...extra,
    });
    const body = (extra: Record<string, unknown> = {}) => ({
      ...validCreateBody,
      hiddenFields: { enabled: true, fieldIds: ["plan"] },
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              id: "pick",
              type: "multipleChoiceMulti",
              headline: { "en-US": "Pick" },
              required: false,
              choices: [option("a", { showIf, ...extra }), option("b", { hidden: true })],
            },
            {
              id: "poster",
              type: "pictureSelection",
              headline: { "en-US": "Poster" },
              required: false,
              choices: [
                { id: "pa", imageUrl: "https://example.com/a.png", hidden: true },
                { id: "pb", imageUrl: "https://example.com/b.png", showIf },
              ],
            },
            {
              id: "grid",
              type: "matrix",
              headline: { "en-US": "Rate" },
              required: false,
              rows: [option("r1", { showIf }), option("r2")],
              columns: [option("c1"), option("c2", { hidden: true })],
            },
          ],
        },
      ],
    });

    const accepted = ZV3CreateSurveyBody.safeParse(body());
    expect(accepted.error?.issues ?? []).toEqual([]);
    const elements = accepted.data?.blocks[0].elements as unknown as Record<
      string,
      Record<string, unknown>[]
    >[];
    expect(elements[0].choices[0].showIf).toEqual(showIf);
    expect(elements[0].choices[1].hidden).toBe(true);
    expect(elements[1].choices[0].hidden).toBe(true);
    expect(elements[2].rows[0].showIf).toEqual(showIf);
    expect(elements[2].columns[1].hidden).toBe(true);

    const rejected = ZV3CreateSurveyBody.safeParse(
      body({ showIf: { ...showIf, conditions: [{ ...showIf.conditions[0], note: "x" }] } })
    );
    expect(rejected.error?.issues.map((issue) => issue.path.join("."))).toContain(
      "blocks.0.elements.0.choices.0.showIf.conditions.0.note"
    );
  });

  test("rejects the internal default translation key in public v3 input", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              headline: { default: "Internal key should not be public" },
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues[0].path.join(".")).toBe("blocks.0.elements.0.headline.default");
  });

  test("preserves arbitrary metadata while normalizing known translatable metadata fields", () => {
    const parsed = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      metadata: {
        cx_context: {
          "de-DE": "This is arbitrary customer metadata, not translation content",
        },
        title: {
          "en-US": "Feedback Survey",
          "de-DE": "Feedback-Umfrage",
        },
      },
    });

    expect(parsed.metadata).toMatchObject({
      cx_context: {
        "de-DE": "This is arbitrary customer metadata, not translation content",
      },
      title: {
        default: "Feedback Survey",
        "de-DE": "Feedback-Umfrage",
      },
    });
  });

  test("accepts link and app survey types for the public create endpoint", () => {
    expect(ZV3CreateSurveyBody.parse(validCreateBody).type).toBe("link");

    const result = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      type: "app",
    });

    expect(result.type).toBe("app");
  });

  test("accepts an app survey with distribution + targeting and applies distribution defaults", () => {
    const result = ZV3CreateSurveyBody.parse({
      ...validCreateBody,
      type: "app",
      distribution: {
        displayOption: "respondMultiple",
        recontactDays: 7,
        triggers: [{ actionClassId: "claa1234567890123456789012" }],
      },
      targeting: { filters: [] },
    });

    expect(result.distribution).toMatchObject({
      displayOption: "respondMultiple",
      recontactDays: 7,
      displayPercentage: null,
      displayLimit: null,
      autoClose: null,
      keepEndingCardOpen: false,
      autoComplete: null,
      delay: 0,
      triggers: [{ actionClassId: "claa1234567890123456789012" }],
    });
    expect(result.targeting).toEqual({ filters: [] });
  });

  test("accepts keepEndingCardOpen in distribution and rejects a non-boolean", () => {
    const base = { ...validCreateBody, type: "app" as const };

    expect(
      ZV3CreateSurveyBody.parse({ ...base, distribution: { keepEndingCardOpen: true } }).distribution
    ).toMatchObject({ keepEndingCardOpen: true });
    expect(
      ZV3CreateSurveyBody.safeParse({ ...base, distribution: { keepEndingCardOpen: "yes" } }).success
    ).toBe(false);
  });

  test("rejects distribution and targeting on link surveys", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "link",
      distribution: { displayOption: "displayOnce" },
      targeting: { filters: [] },
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({ name: "distribution", code: "unsupported_field" }),
          expect.objectContaining({ name: "targeting", code: "unsupported_field" }),
        ])
      );
    }
  });

  test("accepts displaySome with displayLimit (show at most N times)", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { displayOption: "displaySome", displayLimit: 3 },
    });

    expect(result.success).toBe(true);
    if (result.success) {
      expect(result.data.distribution).toMatchObject({ displayOption: "displaySome", displayLimit: 3 });
    }
  });

  test("requires displayLimit >= 1 when displayOption is displaySome", () => {
    const noLimit = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { displayOption: "displaySome" },
    });
    expect(noLimit.success).toBe(false);
    if (!noLimit.success) {
      expect(formatV3ZodInvalidParams(noLimit.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "distribution.displayLimit",
            code: "missing_required_field",
          }),
        ])
      );
    }

    const zeroLimit = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { displayOption: "displaySome", displayLimit: 0 },
    });
    expect(zeroLimit.success).toBe(false);
  });

  describe("distribution.showConditions", () => {
    const cmsRule = {
      id: "grp1",
      connector: "and",
      conditions: [
        {
          id: "cnd1",
          leftOperand: { type: "page", value: "currentUrl" },
          operator: "containsAnyOf",
          rightOperand: { type: "static", value: ["/plan-compare", "/drug-coverage"] },
        },
        {
          id: "grp2",
          connector: "or",
          conditions: [
            {
              id: "cnd2",
              leftOperand: { type: "visit", value: "timeOnSite" },
              operator: "isGreaterThanOrEqual",
              rightOperand: { type: "static", value: 120 },
            },
            {
              id: "cnd3",
              leftOperand: { type: "visit", value: "pagesViewed" },
              operator: "isGreaterThanOrEqual",
              rightOperand: { type: "static", value: 3 },
            },
          ],
        },
      ],
    };

    test("accepts a rule and defaults to null when omitted", () => {
      const withRule = ZV3CreateSurveyBody.safeParse({
        ...validCreateBody,
        type: "app",
        distribution: { showConditions: cmsRule },
      });
      const without = ZV3CreateSurveyBody.safeParse({ ...validCreateBody, type: "app", distribution: {} });

      expect(withRule.success && withRule.data.distribution?.showConditions).toEqual(cmsRule);
      expect(without.success && without.data.distribution?.showConditions).toBeNull();
    });

    test("stores an empty group as null", () => {
      const result = ZV3CreateSurveyBody.safeParse({
        ...validCreateBody,
        type: "app",
        distribution: { showConditions: { id: "grp1", connector: "and", conditions: [] } },
      });

      expect(result.success && result.data.distribution?.showConditions).toBeNull();
    });

    test("refuses a condition that cannot work, pointing at the field", () => {
      const result = ZV3CreateSurveyBody.safeParse({
        ...validCreateBody,
        type: "app",
        distribution: {
          showConditions: {
            id: "grp1",
            connector: "and",
            conditions: [
              {
                id: "cnd1",
                leftOperand: { type: "visit", value: "pagesViewed" },
                operator: "contains",
                rightOperand: { type: "static", value: "3" },
              },
            ],
          },
        },
      });

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
          expect.arrayContaining([
            expect.objectContaining({ name: "distribution.showConditions.conditions.0.operator" }),
          ])
        );
      }
    });
  });

  test("accepts displayPercentage with any displayOption (independent throttle)", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { displayOption: "displayOnce", displayPercentage: 50 },
    });

    expect(result.success).toBe(true);
    if (result.success) {
      expect(result.data.distribution).toMatchObject({ displayOption: "displayOnce", displayPercentage: 50 });
    }
  });

  test("rejects unsupported fields inside distribution", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { displayOption: "displayOnce", surprise: true },
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({ name: "distribution.surprise", code: "unsupported_field" }),
        ])
      );
    }
  });

  test("rejects a malformed trigger action class id", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      type: "app",
      distribution: { triggers: [{ actionClassId: "not-a-cuid" }] },
    });

    expect(result.success).toBe(false);
  });

  test("rejects malformed locale maps that do not include the default language", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              ...validCreateBody.blocks[0].elements[0],
              headline: { "not a locale": "Hello" },
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "blocks.0.elements.0.headline.not a locale",
            reason: "Language key 'not a locale' is not a valid locale code",
            code: "invalid_locale",
          }),
        ])
      );
    }
  });

  test("reports missing required element fields before shared element union errors", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [
            {
              id: "feedback",
              type: "openText",
              headline: { "en-US": "Tell us more" },
            },
          ],
        },
      ],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "blocks.0.elements.0.required",
            reason: "Missing required field 'required' for element type 'openText'",
            code: "missing_required_field",
          }),
        ])
      );
    }
  });

  // ENG-4100: an incomplete element is four problems, and 49k `{}` entries fit in 150 KB. The document
  // pre-pass must stop building them at the response cap, not after the Zod parse has held them all.
  describe("document pre-pass cap", () => {
    const incompleteElements = (count: number) => Array.from({ length: count }, () => ({}));
    const withElements = (elements: unknown[]) => ({
      ...validCreateBody,
      blocks: [{ ...validCreateBody.blocks[0], elements }],
    });

    test("holds at most the response cap of issues however many entries are incomplete", () => {
      const result = ZV3CreateSurveyBody.safeParse(withElements(incompleteElements(1000)));

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(V3_INVALID_PARAMS_MAX);
      }
    });

    test("still counts every problem it did not list", () => {
      const result = ZV3CreateSurveyBody.safeParse(withElements(incompleteElements(1000)));

      expect(result.success).toBe(false);
      if (!result.success) {
        const params = formatV3ZodInvalidParams(result.error, "body");
        expect(params).toHaveLength(V3_INVALID_PARAMS_MAX);
        expect(params[0]).toMatchObject({
          name: "blocks.0.elements.0.id",
          code: "missing_required_field",
        });
        // 1,000 elements x 4 missing fields, minus the 49 listed.
        expect(params.at(-1)?.reason).toBe(
          "3951 further problems with this survey document were not reported; fix the ones above and retry"
        );
      }
    });

    test("lists every problem, with no summary, while they fit under the cap", () => {
      const result = ZV3CreateSurveyBody.safeParse(withElements(incompleteElements(12)));

      expect(result.success).toBe(false);
      if (!result.success) {
        const params = formatV3ZodInvalidParams(result.error, "body");
        expect(params).toHaveLength(48);
        expect(params.every((param) => param.code === "missing_required_field")).toBe(true);
      }
    });

    test("applies to a patch body too", () => {
      const result = ZV3PatchSurveyBody.safeParse({
        blocks: [{ ...validCreateBody.blocks[0], elements: incompleteElements(1000) }],
      });

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(V3_INVALID_PARAMS_MAX);
      }
    });
  });

  test("accepts hideDefaultIcon on an end screen ending", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      endings: [
        {
          id: "clend123456789012345678901",
          type: "endScreen",
          headline: { "en-US": "Thanks!" },
          hideDefaultIcon: true,
        },
      ],
    });

    expect(result.success).toBe(true);
    if (result.success) {
      expect(result.data.endings?.[0]).toMatchObject({ hideDefaultIcon: true });
    }
  });

  // ENG-4100: whatever the shape, a document inside the request budgets builds no more than the reply
  // lists. Each case is one a review measured at 50k-1.2M issues (or a stack overflow) before the guard.
  describe("bounded parse", () => {
    const repeat = <T>(count: number, entry: () => T): T[] => Array.from({ length: count }, entry);
    const label = { "en-US": "Label" };
    const element = (extra: Record<string, unknown>, type = "multipleChoiceSingle") => ({
      id: "q1",
      type,
      headline: label,
      required: true,
      ...extra,
    });
    const block = (
      extra: Record<string, unknown> = {},
      elements: unknown[] = [element({ choices: [] })]
    ) => ({
      id: "clbk1234567890123456789012",
      name: "Block",
      elements,
      ...extra,
    });
    const group = (conditions: unknown[]) => ({ id: "g1", connector: "and", conditions });
    const withLogic = (count: number, logic: () => unknown) =>
      ({ ...validCreateBody, blocks: repeat(count, () => block({ logic: [logic()] })) }) as const;

    test.each<[string, () => unknown]>([
      [
        "choices with wrong values",
        () => ({
          ...validCreateBody,
          blocks: [
            block(
              {},
              repeat(49, () => element({ choices: repeat(1000, () => ({ id: 0, label: 0 })) }))
            ),
          ],
        }),
      ],
      [
        "elements with wrong values",
        () => ({
          ...validCreateBody,
          blocks: repeat(39, () =>
            block(
              {},
              repeat(1000, () => ({ id: 0, type: "openText", headline: 0, required: 0 }))
            )
          ),
        }),
      ],
      [
        "conditions with wrong values, every union branch failing",
        () =>
          withLogic(40, () => ({
            id: "l1",
            conditions: group(
              repeat(1000, () => ({ id: 0, leftOperand: {}, operator: 0, rightOperand: {} }))
            ),
            actions: [],
          })),
      ],
      [
        "calculate actions with wrong values",
        () =>
          withLogic(30, () => ({
            id: "l1",
            conditions: group([]),
            actions: repeat(1000, () => ({
              id: 0,
              objective: "calculate",
              variableId: 0,
              operator: 0,
              value: 0,
            })),
          })),
      ],
      [
        "validation rules with wrong params",
        () => ({
          ...validCreateBody,
          blocks: [
            block(
              {},
              repeat(49, () =>
                element(
                  {
                    validation: {
                      rules: repeat(1000, () => ({ id: "r", type: "minLength", params: { x: 1 } })),
                    },
                  },
                  "openText"
                )
              )
            ),
          ],
        }),
      ],
      [
        "nested show-condition groups of empty conditions",
        () => ({
          ...validCreateBody,
          type: "app",
          distribution: { showConditions: group(repeat(49, () => group(repeat(1000, () => ({}))))) },
        }),
      ],
    ])("%s", (_name, build) => {
      const body = build();
      expect(findArrayBudgetViolation(body)).toBeNull();

      const result = ZV3CreateSurveyBody.safeParse(body);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(V3_INVALID_PARAMS_MAX);
      }
    });

    // The guard looks a catchall's extra keys up by own key: `metadata.constructor` once resolved to
    // `Object` and threw, a 500 for a valid body.
    test("takes big metadata with keys named like prototype members", () => {
      const metadata = {
        ...(JSON.parse('{"constructor":1,"toString":"x","__proto__":{"a":1}}') as Record<string, unknown>),
        pad: repeat(300, () => 1),
      };

      expect(ZV3CreateSurveyBody.safeParse({ ...validCreateBody, metadata }).success).toBe(true);
    });

    // Zod skips a record's own `__proto__` key; the guard once walked it and refused a valid body.
    test("takes a logic operand's big meta with a `__proto__` key", () => {
      const meta = {
        ...(JSON.parse('{"__proto__":1}') as Record<string, unknown>),
        ...Object.fromEntries(repeat(300, () => 0).map((_zero, index) => [`k${index}`, "x"])),
      };
      const condition = {
        id: "c1",
        leftOperand: { type: "element", value: "q1", meta },
        operator: "isSubmitted",
      };
      const body = {
        ...validCreateBody,
        blocks: [
          {
            ...validCreateBody.blocks[0],
            logic: [{ id: "l1", conditions: group([condition]), actions: [] }],
          },
        ],
      };

      expect(ZV3CreateSurveyBody.safeParse(body).success).toBe(true);
    });

    // One bad leaf under a deep chain of condition groups with big valid levels: a guard that checks a
    // level's whole subtree at every level spent ~9 s here for one issue. The timeout is a complexity
    // guard, not a benchmark: the linear walk needs well under 100 ms.
    test("one error deep in a wide condition tree costs one pass", () => {
      const condition = (index: number) => ({
        id: `c${index}`,
        leftOperand: { type: "element", value: "q1" },
        operator: "isSubmitted",
      });
      let tree: unknown = group([{ ...condition(0), operator: "zzz" }]);
      for (let depth = 0; depth < 118; depth += 1) {
        tree = { ...group([...repeat(200, () => condition(depth)), tree]), id: `g${depth}` };
      }
      const body = {
        ...validCreateBody,
        blocks: [{ ...validCreateBody.blocks[0], logic: [{ id: "l1", conditions: tree, actions: [] }] }],
      };
      expect(findArrayBudgetViolation(body)).toBeNull();

      const result = ZV3CreateSurveyBody.safeParse(body);

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(1);
      }
    }, 2_000);

    // An element union is split by its `type`, so an ordinary mistake reads as one problem, not one per
    // element type.
    test.each<[string, Record<string, unknown>]>([
      ["a missing field", element({})],
      ["an unknown type", element({ choices: [] }, "nope")],
    ])("reports %s in one big block as one problem", (_name, broken) => {
      const fine = (index: number) =>
        element({
          id: `q${index + 2}`,
          choices: [
            { id: "a", label },
            { id: "b", label },
          ],
        });
      const result = ZV3CreateSurveyBody.safeParse({
        ...validCreateBody,
        blocks: [block({}, [broken, ...Array.from({ length: 300 }, (_unused, index) => fine(index))])],
      });

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(1);
      }
    });

    test("applies to a patch body too", () => {
      const result = ZV3PatchSurveyBody.safeParse({
        blocks: [
          block(
            {},
            repeat(49, () => element({ choices: repeat(1000, () => ({ id: 0, label: 0 })) }))
          ),
        ],
      });

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues).toHaveLength(V3_INVALID_PARAMS_MAX);
      }
    });
  });

  describe("translation count", () => {
    const withHeadline = (headline: Record<string, string>) => ({
      ...validCreateBody,
      blocks: [
        {
          ...validCreateBody.blocks[0],
          elements: [{ ...validCreateBody.blocks[0].elements[0], headline }],
        },
      ],
    });
    const translations = (keys: string[]) => Object.fromEntries(keys.map((key) => [key, "Label"]));

    test("refuses a field with more translations than the cap, in one problem", () => {
      const keys = Array.from({ length: V3_SURVEY_MAX_TRANSLATIONS + 1 }, (_unused, index) => `k${index}`);
      const result = ZV3CreateSurveyBody.safeParse(withHeadline(translations(keys)));

      expect(result.success).toBe(false);
      if (!result.success) {
        expect(formatV3ZodInvalidParams(result.error, "body")).toEqual([
          {
            name: "blocks.0.elements.0.headline",
            reason: `Too big: expected at most ${V3_SURVEY_MAX_TRANSLATIONS} translations`,
            code: "limit_exceeded",
          },
        ]);
      }
    });

    // ENG-4100: a cap per field alone let 600 fields of 255 distinct keys through, ~6 s of locale lookups
    // on a body that then parsed. Distinct keys are capped across the whole document.
    test("refuses distinct translation keys spread over many fields, in one problem", () => {
      const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      const locale = (index: number) => `aa-${letters[Math.floor(index / 26) % 26]}${letters[index % 26]}`;
      const field = (offset: number) =>
        translations(["en-US", ...Array.from({ length: 200 }, (_unused, index) => locale(offset + index))]);
      const elements = [0, 200].map((offset, index) => ({
        ...validCreateBody.blocks[0].elements[0],
        id: `q${index}`,
        headline: field(offset),
      }));

      const result = ZV3CreateSurveyBody.safeParse({
        ...validCreateBody,
        blocks: [{ ...validCreateBody.blocks[0], elements }],
      });

      expect(result.success).toBe(false);
      if (!result.success) {
        // Some generated region codes canonicalize onto others and add their own `duplicate_locale`
        // problems; what matters is the one refusal of the count.
        expect(
          formatV3ZodInvalidParams(result.error, "body").filter((param) => param.code === "limit_exceeded")
        ).toEqual([
          {
            name: "blocks.0.elements.1.headline",
            reason: `Too big: expected at most ${V3_SURVEY_MAX_DOCUMENT_LOCALE_KEYS} distinct translation keys in the survey`,
            code: "limit_exceeded",
          },
        ]);
      }
    });

    test("takes a field with exactly the cap's translations", () => {
      const keys = Array.from({ length: V3_SURVEY_MAX_TRANSLATIONS }, (_unused, index) => `k${index}`);
      const result = ZV3CreateSurveyBody.safeParse(withHeadline(translations(keys)));
      const params = result.success ? [] : formatV3ZodInvalidParams(result.error, "body");

      expect(params.filter((param) => param.code === "limit_exceeded")).toEqual([]);
    });

    // The cap must never refuse a stored survey: a field holds one key per survey language, and every
    // language comes from the catalog.
    test("sits above a field translated into every catalog locale", () => {
      expect(CANONICAL_LANGUAGE_CODES.length).toBeLessThan(V3_SURVEY_MAX_TRANSLATIONS);

      const result = ZV3CreateSurveyBody.safeParse(withHeadline(translations([...CANONICAL_LANGUAGE_CODES])));
      const reasons = result.success
        ? []
        : formatV3ZodInvalidParams(result.error, "body").map((p) => p.reason);

      expect(reasons).not.toContainEqual(expect.stringContaining("translations"));
    });
  });

  describe("image alt text", () => {
    const pictureElement = {
      id: "favourite",
      type: "pictureSelection",
      headline: { "en-US": "Pick one" },
      required: true,
      allowMulti: false,
      imageUrl: "https://example.com/hero.jpg",
      imageAltText: { "en-US": "Product hero shot" },
      choices: [
        { id: "a", imageUrl: "https://example.com/a.jpg", imageAltText: { "en-US": "Blue mug" } },
        { id: "b", imageUrl: "https://example.com/b.jpg" },
      ],
    };
    const endingWithImage = {
      id: "clend123456789012345678901",
      type: "endScreen",
      headline: { "en-US": "Thanks!" },
      imageUrl: "https://example.com/thanks.jpg",
      imageAltText: { "en-US": "Team waving" },
    };
    const bodyWith = (element: object, ending: object) => ({
      ...validCreateBody,
      blocks: [{ ...validCreateBody.blocks[0], elements: [element] }],
      endings: [ending],
    });

    test("accepts it on elements, picture choices and end screens, keyed to the default language", () => {
      const result = ZV3CreateSurveyBody.safeParse(bodyWith(pictureElement, endingWithImage));

      expect(result.error).toBeUndefined();
      const element = result.data?.blocks[0].elements[0];
      expect(element).toMatchObject({ imageAltText: { default: "Product hero shot" } });
      expect(element).toMatchObject({
        choices: [{ imageAltText: { default: "Blue mug" } }, { id: "b" }],
      });
      expect(result.data?.endings?.[0]).toMatchObject({ imageAltText: { default: "Team waving" } });
    });

    test("rejects the internal default key in a picture choice's alt text", () => {
      const result = ZV3CreateSurveyBody.safeParse(
        bodyWith(
          {
            ...pictureElement,
            choices: [
              { ...pictureElement.choices[0], imageAltText: { default: "Blue mug" } },
              pictureElement.choices[1],
            ],
          },
          endingWithImage
        )
      );

      expect(result.success).toBe(false);
      expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
        "blocks.0.elements.0.choices.0.imageAltText.default"
      );
    });

    test("accepts an empty alt text with no translations as a decorative image", () => {
      const result = ZV3CreateSurveyBody.safeParse({
        ...bodyWith(
          {
            ...pictureElement,
            headline: { "en-US": "Pick one", "de-DE": "Wähle eins" },
            imageAltText: { "en-US": "" },
            choices: pictureElement.choices.map((choice) => ({ ...choice, imageAltText: { "en-US": "" } })),
          },
          {
            ...endingWithImage,
            headline: { "en-US": "Thanks!", "de-DE": "Danke!" },
            imageAltText: { "en-US": "" },
          }
        ),
        languages: [{ code: "de-DE" }],
      });

      expect(result.error).toBeUndefined();
    });
  });

  test("reports missing required ending fields before shared ending union errors", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      endings: [
        {
          type: "endScreen",
          headline: { "en-US": "Thanks!" },
        },
      ],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "endings.0.id",
            reason: "Missing required field 'id' for ending type 'endScreen'",
            code: "missing_required_field",
          }),
        ])
      );
    }
  });

  test("reports missing ending type with a precise invalid param path", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      endings: [
        {
          id: "clend123456789012345678901",
          headline: { "en-US": "Thanks!" },
        },
      ],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "endings.0.type",
            reason: "Missing required field 'type' for survey ending",
            code: "missing_required_field",
          }),
        ])
      );
    }
  });

  test("rejects duplicate language entries and disabled default language", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      languages: [{ code: "en-US", enabled: false }, { code: "en_us" }],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "languages.0.enabled",
            reason: "The default language cannot be disabled",
          }),
          expect.objectContaining({
            name: "languages.1.code",
            reason: "Language 'en-US' is duplicated",
            code: "duplicate_locale",
          }),
        ])
      );
    }
  });

  test("reports invalid language entries with machine-readable locale metadata", () => {
    const result = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      languages: [{ code: "de", enabled: true }],
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            name: "languages.0.code",
            reason: "Language 'de' is not a valid locale code",
            code: "invalid_locale",
          }),
        ])
      );
    }
  });
});

describe("ZV3PatchSurveyBody", () => {
  test("accepts a strict top-level partial and preserves omitted defaults", () => {
    const parsed = ZV3PatchSurveyBody.parse({
      name: "Updated survey",
    });

    expect(parsed).toEqual({ name: "Updated survey" });
  });

  test("accepts the language settings, with null clearing and omission leaving them unchanged", () => {
    expect(ZV3PatchSurveyBody.parse({ showLanguageSwitch: true, autoSelectLanguage: false })).toEqual({
      showLanguageSwitch: true,
      autoSelectLanguage: false,
    });
    expect(ZV3PatchSurveyBody.parse({ autoSelectLanguage: null })).toEqual({ autoSelectLanguage: null });
    expect(ZV3PatchSurveyBody.safeParse({ autoSelectLanguage: "yes" }).success).toBe(false);
  });

  test("rejects an empty patch body", () => {
    const result = ZV3PatchSurveyBody.safeParse({});

    expect(result.success).toBe(false);
    expect(result.error?.issues[0]).toMatchObject({
      message: "Request body must include at least one updatable field",
    });
  });

  test("rejects immutable and out-of-scope fields", () => {
    const result = ZV3PatchSurveyBody.safeParse({
      id: "clsv1234567890123456789012",
      workspaceId: "clxx1234567890123456789012",
      type: "link",
      defaultLanguage: "de-DE",
      questions: [],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
      expect.arrayContaining(["id", "workspaceId", "type", "defaultLanguage", "questions"])
    );
  });

  test("rejects patch languages that mark a non-current locale as default", () => {
    const result = createZV3PatchSurveyBodySchema("en-US").safeParse({
      languages: [{ code: "de-DE", default: true, enabled: true }],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues[0]).toMatchObject({
      message: "The default language entry must match defaultLanguage",
      path: ["languages", 0, "default"],
    });
  });

  test("accepts patch languages that keep the current default locale", () => {
    const parsed = createZV3PatchSurveyBodySchema("en-US").parse({
      languages: [
        { code: "en_us", default: true, enabled: true },
        { code: "de-DE", enabled: false },
      ],
    });

    expect(parsed.languages).toEqual([
      { code: "en-US", default: true, enabled: true },
      { code: "de-DE", enabled: false },
    ]);
  });

  test("normalizes patch translation maps using the current default language", () => {
    const parsed = createZV3PatchSurveyBodySchema("de-DE").parse({
      blocks: [
        {
          id: "clbk1234567890123456789012",
          name: "Main Block",
          elements: [
            {
              id: "satisfaction",
              type: "openText",
              headline: { de_de: "Hallo", en_us: "Hello" },
              required: true,
            },
          ],
        },
      ],
    });

    expect(parsed.blocks?.[0].elements[0]).toMatchObject({
      headline: { default: "Hallo", "en-US": "Hello" },
    });
    expect(parsed).not.toHaveProperty("defaultLanguage");
  });

  test("allows existing legacy language codes only through the patch compatibility context", () => {
    const parsed = createZV3PatchSurveyBodySchema("gu", {
      allowedLanguageCodes: ["gu"],
    }).parse({
      metadata: {
        title: { gu: "Legacy Gujarati survey" },
      },
      languages: [{ code: "gu", default: true, enabled: true }],
    });

    expect(parsed).toMatchObject({
      metadata: { title: { default: "Legacy Gujarati survey" } },
      languages: [{ code: "gu", default: true, enabled: true }],
    });
  });

  test("rejects newly introduced non-canonical patch languages without compatibility context", () => {
    const result = createZV3PatchSurveyBodySchema("en-US", {
      allowedLanguageCodes: ["en-US"],
    }).safeParse({
      languages: [{ code: "gu", enabled: true }],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues[0]).toMatchObject({
      message: "Language 'gu' is not a valid locale code",
      path: ["languages", 0, "code"],
    });
  });

  test("does not generate missing ids for canonical patch documents", () => {
    const result = ZV3PatchSurveyBody.safeParse({
      blocks: [
        {
          name: "Missing ID Block",
          elements: validCreateBody.blocks[0].elements,
        },
      ],
      variables: [
        {
          name: "score",
          type: "number",
          value: 0,
        },
      ],
    });

    expect(result.success).toBe(false);
    expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
      expect.arrayContaining(["blocks.0.id", "variables.0.id"])
    );
  });

  test("rejects distribution and targeting when patching a link survey", () => {
    const result = createZV3PatchSurveyBodySchema("en-US", undefined, "link").safeParse({
      distribution: { displayOption: "displayOnce" },
      targeting: { filters: [] },
    });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({ name: "distribution", code: "unsupported_field" }),
          expect.objectContaining({ name: "targeting", code: "unsupported_field" }),
        ])
      );
    }
  });

  test("accepts distribution and targeting when patching an app survey", () => {
    const parsed = createZV3PatchSurveyBodySchema("en-US", undefined, "app").parse({
      distribution: { displayOption: "displayMultiple" },
      targeting: { filters: [] },
    });

    expect(parsed.distribution).toMatchObject({ displayOption: "displayMultiple" });
    expect(parsed.targeting).toEqual({ filters: [] });
  });
});

describe("formatV3ZodInvalidParams", () => {
  // Built from the real validator rather than a literal message: the marker only reaches clients
  // because these shared validators embed it, so a hand-written fixture would assert nothing.
  const buildBlankTranslationIssue = (): z.core.$ZodIssue => {
    const language = {
      id: "clln1234567890123456789012",
      code: "de-DE",
      alias: null,
      workspaceId: "clxx1234567890123456789012",
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    const issue = validateElementLabels(
      "headline",
      { default: "What should we improve?", "de-DE": "   " },
      [
        {
          language: { ...language, id: "clle1234567890123456789012", code: "en-US" },
          default: true,
          enabled: true,
        },
        { language, default: false, enabled: true },
      ],
      0,
      0
    );

    if (!issue) {
      throw new Error("expected the label validator to reject a blank translation");
    }

    return issue as z.core.$ZodIssue;
  };

  test("strips the editor-only -fLang- delimiter from the reason", () => {
    const issue = buildBlankTranslationIssue();
    expect(issue.message).toContain("-fLang-");

    const [invalidParam] = formatV3ZodInvalidParams(new z.ZodError([issue]), "body");

    expect(invalidParam.reason).not.toContain("-fLang-");
    expect(invalidParam.reason).toBe(
      "The question in question 1 of block 1 is missing for the following languages: de-DE"
    );
    expect(invalidParam.name).toBe("blocks.0.elements.0.headline");
  });

  test("leaves a reason without the delimiter untouched", () => {
    const result = ZV3CreateSurveyBody.safeParse({ ...validCreateBody, defaultLanguage: "not a locale" });

    expect(result.success).toBe(false);
    if (!result.success) {
      expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
        expect.arrayContaining([
          expect.objectContaining({ reason: "Language 'not a locale' is not a valid locale code" }),
        ])
      );
    }
  });

  test("normalizes the comma-joined ending-card shape too", () => {
    const issue = {
      code: "custom",
      message:
        "The button label on the Ending card 2 is missing for the following languages:  -fLang- de, fr",
      path: ["endings", 1, "buttonLabel"],
    } as z.core.$ZodIssue;

    const [invalidParam] = formatV3ZodInvalidParams(new z.ZodError([issue]), "body");

    expect(invalidParam.reason).toBe(
      "The button label on the Ending card 2 is missing for the following languages: de, fr"
    );
  });

  // A caller-supplied language code reaches `reason` verbatim (createZV3SurveyLanguageTag interpolates
  // it and only trims the ends), so a long interior whitespace run is reachable from one request. The
  // previous `/\s*-fLang-\s*/` implementation was quadratic on exactly that input — ~5s server-side at
  // 100k characters. The timeout is a complexity guard, not a benchmark: the linear implementation
  // needs microseconds, so the margin here is several orders of magnitude.
  test.each([
    ["no marker present", 100_000, false],
    ["marker present", 100_000, true],
  ])(
    "stays linear on a %s whitespace run",
    (_label, runLength, withMarker) => {
      const run = " ".repeat(runLength);
      const message = withMarker
        ? `Language 'a${run}b' is not valid: -fLang- de-DE`
        : `Language 'a${run}b' is not a valid locale code`;
      const issue = { code: "custom", message, path: ["languages", 0, "code"] } as z.core.$ZodIssue;

      const [invalidParam] = formatV3ZodInvalidParams(new z.ZodError([issue]), "body");

      // Whole expected string, not fragments: the caller's interior run survives untouched, only the
      // marker and the whitespace adjoining it are collapsed, and a marker-free message is identical,
      // up to the reply's echo limit (ENG-4100).
      const expected = withMarker ? `Language 'a${run}b' is not valid: de-DE` : message;
      expect(invalidParam.reason).toBe(`${expected.slice(0, V3_INVALID_PARAM_REASON_MAX_CHARS)}…`);
    },
    2_000
  );
});

describe("block operation bodies are bounded (ENG-1652)", () => {
  // The response-side diagnostics cap has its own tests; these pin the *input* bounds, which carry
  // the abuse-cost argument — an unbounded op list is quadratic in `applySurveyBlockOperations`, an
  // unbounded id is echoed into `invalid_params[].reason`, and an unbounded order is the amplification
  // fixed on this branch. Delete any of the `.max()` calls and the matching case here goes red.
  const removeOps = (count: number, id = "blk_a") =>
    Array.from({ length: count }, () => ({ op: "remove", id }));

  test("accepts exactly the op-list cap and refuses one more", () => {
    expect(ZV3EditSurveyBlocksBody.safeParse({ ops: removeOps(V3_SURVEY_BLOCK_OPS_MAX) }).success).toBe(true);
    expect(ZV3EditSurveyBlocksBody.safeParse({ ops: removeOps(V3_SURVEY_BLOCK_OPS_MAX + 1) }).success).toBe(
      false
    );
  });

  test("bounds every block reference at 128 characters, trimmed, non-empty", () => {
    const ok = "a".repeat(128);
    const long = "a".repeat(129);

    expect(ZV3EditSurveyBlocksBody.safeParse({ ops: removeOps(1, ok) }).success).toBe(true);
    expect(ZV3EditSurveyBlocksBody.safeParse({ ops: removeOps(1, long) }).success).toBe(false);
    expect(ZV3SetSurveyBlockOrderBody.safeParse({ order: [long] }).success).toBe(false);
    // Whitespace-only is empty after trim, which is what the contract's `minLength: 1` documents.
    expect(ZV3SetSurveyBlockOrderBody.safeParse({ order: ["   "] }).success).toBe(false);
    expect(ZV3SetSurveyBlockOrderBody.safeParse({ order: [" blk_a "] })).toMatchObject({
      success: true,
      data: { order: ["blk_a"] },
    });
  });

  test("accepts exactly the order cap and refuses one more", () => {
    const ids = (count: number) => Array.from({ length: count }, (_unused, index) => `blk_${index}`);

    expect(ZV3SetSurveyBlockOrderBody.safeParse({ order: ids(V3_SURVEY_BLOCK_ORDER_MAX) }).success).toBe(
      true
    );
    expect(ZV3SetSurveyBlockOrderBody.safeParse({ order: ids(V3_SURVEY_BLOCK_ORDER_MAX + 1) }).success).toBe(
      false
    );
  });

  test("an oversized array costs one issue, not one per element — on REST and through the MCP SDK's validate", async () => {
    // Zod parses every element before `.max()` fires: 200k junk entries measured at ~500 MB of heap and
    // a multi-megabyte error body. `lengthBoundedArray` checks the length first. `~standard.validate`
    // is the entry point @modelcontextprotocol/server uses for tool arguments, ahead of the scope gate,
    // so it has to be bounded by the schema itself rather than by a check in the REST operation.
    const junk = Array.from({ length: 5000 }, () => 0);

    const order = ZV3SetSurveyBlockOrderBody.safeParse({ order: junk });
    expect(order.success).toBe(false);
    if (!order.success) {
      expect(order.error.issues).toHaveLength(1);
      expect(formatV3ZodInvalidParams(order.error, "body")).toEqual([
        expect.objectContaining({
          name: "order",
          reason: `Too big: expected array to have <=${V3_SURVEY_BLOCK_ORDER_MAX} items`,
        }),
      ]);
    }

    const ops = ZV3EditSurveyBlocksBody.safeParse({ ops: junk });
    expect(ops.success).toBe(false);
    if (!ops.success) {
      expect(ops.error.issues).toHaveLength(1);
    }

    const viaStandard = await ZV3SetSurveyBlockOrderBody["~standard"].validate({ order: junk });
    expect(viaStandard.issues).toHaveLength(1);
  });

  test("still advertises the item shape and both bounds in the JSON schema the MCP tools publish", () => {
    // A `.pipe()` around the field would turn the advertised `items` into `{}` under `io: "input"`; the
    // field-level preprocess must not.
    const json = z.toJSONSchema(ZV3EditSurveyBlocksBody, { io: "input", unrepresentable: "any" }) as {
      properties: Record<string, Record<string, unknown>>;
    };

    expect(json.properties.ops).toMatchObject({
      type: "array",
      minItems: 1,
      maxItems: V3_SURVEY_BLOCK_OPS_MAX,
    });
    expect(JSON.stringify(json.properties.ops.items)).toContain('"remove"');
  });
});

// ENG-3282 (contract §2): visibility is decided by the principal on create and changed only through
// `POST …/visibility`, so both write bodies refuse it — and the owner — as an unsupported field.
describe("survey visibility is not writable through the survey document", () => {
  test.each(["visibility", "ownerId", "owner"])("create refuses `%s` with unsupported_field", (field) => {
    const result = ZV3CreateSurveyBody.safeParse({ ...validCreateBody, [field]: "restricted" });

    expect(result.success).toBe(false);
    if (result.success) return;
    expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
      expect.arrayContaining([expect.objectContaining({ name: field, code: "unsupported_field" })])
    );
  });

  test.each(["visibility", "ownerId", "owner"])("PATCH refuses `%s` with unsupported_field", (field) => {
    const result = ZV3PatchSurveyBody.safeParse({ name: "Renamed", [field]: "restricted" });

    expect(result.success).toBe(false);
    if (result.success) return;
    expect(formatV3ZodInvalidParams(result.error, "body")).toEqual(
      expect.arrayContaining([expect.objectContaining({ name: field, code: "unsupported_field" })])
    );
  });
});

/**
 * The top-level arrays of a survey document had no ceiling, and Zod parses every element before an
 * array-level `.max()` would run — so a 2 MB body of junk entries cost one issue per entry on
 * `POST /api/v3/surveys` before workspace authorization (ENG-3384). Each is now length-bounded ahead of
 * its elements, on create, on patch and through the MCP SDK's `~standard.validate`.
 */
describe("top-level array bounds (ENG-3384)", () => {
  const repeat = <T>(value: T, count: number): T[] => Array.from({ length: count }, () => value);
  const ending = { id: "clend123456789012345678901", type: "endScreen", headline: { "en-US": "Thanks" } };
  const variable = { id: "clvar123456789012345678901", name: "score", type: "number", value: 0 };
  const trigger = { actionClassId: "clact123456789012345678901" };
  const fieldIds = (count: number) => Array.from({ length: count }, (_unused, index) => `field_${index}`);
  const embeddedFields = (count: number) =>
    Array.from({ length: count }, (_unused, index) => ({ name: `field_${index}`, source: "ingested" }));
  const startRule = {
    id: "clrul123456789012345678901",
    conditions: { id: "g", connector: "and", conditions: [] },
    actions: [],
  };

  const cases: [string, string[], Record<string, unknown>, Record<string, unknown>][] = [
    [
      "languages",
      ["languages"],
      { languages: repeat({ code: "de-DE" }, V3_SURVEY_MAX_LANGUAGES + 1) },
      { languages: repeat({ code: "de-DE" }, V3_SURVEY_MAX_LANGUAGES + 1) },
    ],
    [
      "blocks",
      ["blocks"],
      { blocks: repeat(validCreateBody.blocks[0], V3_SURVEY_MAX_BLOCKS + 1) },
      { blocks: repeat(validCreateBody.blocks[0], V3_SURVEY_MAX_BLOCKS + 1) },
    ],
    [
      "endings",
      ["endings"],
      { endings: repeat(ending, V3_SURVEY_MAX_ENDINGS + 1) },
      { endings: repeat(ending, V3_SURVEY_MAX_ENDINGS + 1) },
    ],
    [
      "variables",
      ["variables"],
      { variables: repeat(variable, V3_SURVEY_MAX_VARIABLES + 1) },
      { variables: repeat(variable, V3_SURVEY_MAX_VARIABLES + 1) },
    ],
    [
      "hiddenFields.fieldIds",
      ["hiddenFields", "fieldIds"],
      { hiddenFields: { enabled: true, fieldIds: fieldIds(V3_SURVEY_MAX_HIDDEN_FIELDS + 1) } },
      { hiddenFields: { enabled: true, fieldIds: fieldIds(V3_SURVEY_MAX_HIDDEN_FIELDS + 1) } },
    ],
    [
      "embeddedFields",
      ["embeddedFields"],
      { embeddedFields: embeddedFields(V3_SURVEY_MAX_EMBEDDED_FIELDS + 1) },
      { embeddedFields: embeddedFields(V3_SURVEY_MAX_EMBEDDED_FIELDS + 1) },
    ],
    [
      "startLogic",
      ["startLogic"],
      { startLogic: repeat(startRule, V3_SURVEY_MAX_START_LOGIC_RULES + 1) },
      { startLogic: repeat(startRule, V3_SURVEY_MAX_START_LOGIC_RULES + 1) },
    ],
    [
      "distribution.triggers",
      ["distribution", "triggers"],
      { type: "app", distribution: { triggers: repeat(trigger, V3_SURVEY_MAX_TRIGGERS + 1) } },
      { distribution: { triggers: repeat(trigger, V3_SURVEY_MAX_TRIGGERS + 1) } },
    ],
  ];

  test.each(cases)(
    "%s over its cap costs one issue on create, on patch and via ~standard.validate",
    async (_name, path, createExtra, patchExtra) => {
      const create = ZV3CreateSurveyBody.safeParse({ ...validCreateBody, ...createExtra });
      expect(create.success).toBe(false);
      if (!create.success) {
        expect(create.error.issues).toHaveLength(1);
        expect(create.error.issues[0]).toMatchObject({
          path,
          message: expect.stringMatching(/^Too big: expected array to have <=\d+ items$/),
        });
      }

      const patch = ZV3PatchSurveyBody.safeParse(patchExtra);
      expect(patch.success).toBe(false);
      if (!patch.success) {
        expect(patch.error.issues).toHaveLength(1);
        expect(patch.error.issues[0]).toMatchObject({ path });
      }

      const viaStandard = await ZV3CreateSurveyBody["~standard"].validate({
        ...validCreateBody,
        ...createExtra,
      });
      expect(viaStandard.issues).toHaveLength(1);
    }
  );

  test("accepts exactly the hidden-field cap and keeps the minimum-blocks message", () => {
    const atCap = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      hiddenFields: { enabled: true, fieldIds: fieldIds(V3_SURVEY_MAX_HIDDEN_FIELDS) },
    });
    expect(atCap.success).toBe(true);

    const embeddedAtCap = ZV3CreateSurveyBody.safeParse({
      ...validCreateBody,
      embeddedFields: embeddedFields(V3_SURVEY_MAX_EMBEDDED_FIELDS),
    });
    expect(embeddedAtCap.success).toBe(true);

    const noBlocks = ZV3CreateSurveyBody.safeParse({ ...validCreateBody, blocks: [] });
    expect(noBlocks.success).toBe(false);
    if (!noBlocks.success) {
      expect(noBlocks.error.issues[0]).toMatchObject({
        path: ["blocks"],
        message: "At least one block is required",
      });
    }
  });

  test("advertises every bound as maxItems in the JSON schema", () => {
    // `io: "output"` because the body is `z.unknown().pipe(...)`, whose input side is `unknown`; the
    // MCP tool schemas (advertised as input) are covered in `modules/mcp/tools/schemas.test.ts`.
    const json = z.toJSONSchema(ZV3CreateSurveyBody, { io: "output", unrepresentable: "any" }) as {
      properties: Record<string, Record<string, unknown>>;
    };

    expect(json.properties.blocks).toMatchObject({
      type: "array",
      minItems: 1,
      maxItems: V3_SURVEY_MAX_BLOCKS,
    });
    expect(json.properties.endings).toMatchObject({ maxItems: V3_SURVEY_MAX_ENDINGS });
    expect(json.properties.variables).toMatchObject({ maxItems: V3_SURVEY_MAX_VARIABLES });
    expect(json.properties.languages).toMatchObject({ maxItems: V3_SURVEY_MAX_LANGUAGES });
    expect(json.properties.hiddenFields).toMatchObject({
      properties: { fieldIds: expect.objectContaining({ maxItems: V3_SURVEY_MAX_HIDDEN_FIELDS }) },
    });
    expect(json.properties.distribution).toMatchObject({
      properties: { triggers: expect.objectContaining({ maxItems: V3_SURVEY_MAX_TRIGGERS }) },
    });
  });
});

describe("ZV3CreateSurveyQuery", () => {
  // Spelled out rather than read from the schema's own list, so dropping a value the dashboard sends —
  // `import` comes from the Qualtrics import dialog (ENG-3653) — fails here.
  test.each(["blank", "template", "xm-template", "ai", "import"])("accepts createdFrom=%s", (createdFrom) => {
    expect(ZV3CreateSurveyQuery.safeParse({ createdFrom }).success).toBe(true);
  });

  test("accepts a create with no createdFrom", () => {
    expect(ZV3CreateSurveyQuery.safeParse({}).success).toBe(true);
  });

  test("rejects an unknown createdFrom, so analytics never records an invented source", () => {
    expect(ZV3CreateSurveyQuery.safeParse({ createdFrom: "qualtrics" }).success).toBe(false);
  });
});
