import { TFunction } from "i18next";
import { describe, expect, test, vi } from "vitest";
import { ZSurveyLogicConditionsOperator } from "@formbricks/types/surveys/logic";
import { TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
import { TLogicRuleOption, getLogicRules } from "./logic-rule-engine";

// Mock the translation function
const mockT = vi.fn((key: string) => `mockTranslate(${key})`);
const logicRules = getLogicRules(mockT as unknown as TFunction);
const elementRules = logicRules.element as Record<string, { options: TLogicRuleOption }>;

/**
 * The expected option runs, named once.
 *
 * Every family's expectation re-spelled these lists in full — the submitted/skipped pair twelve
 * times over — which is duplicated code to Sonar and, more to the point, buries what actually
 * differs between one family's operators and the next.
 */
const OPT = (key: string, op: keyof typeof ZSurveyLogicConditionsOperator.enum) => ({
  label: `mockTranslate(workspace.surveys.edit.${key})`,
  value: ZSurveyLogicConditionsOperator.enum[op],
});

const EQUALITY = [OPT("equals", "equals"), OPT("does_not_equal", "doesNotEqual")];

const TEXT_OPERATORS = [
  ...EQUALITY,
  OPT("contains", "contains"),
  OPT("does_not_contain", "doesNotContain"),
  OPT("starts_with", "startsWith"),
  OPT("does_not_start_with", "doesNotStartWith"),
  OPT("ends_with", "endsWith"),
  OPT("does_not_end_with", "doesNotEndWith"),
];

/** Symbol-labelled on purpose: the numeric families never showed the worded equality pair. */
const NUMBER_COMPARISONS = [
  { label: "=", value: ZSurveyLogicConditionsOperator.enum.equals },
  { label: "!=", value: ZSurveyLogicConditionsOperator.enum.doesNotEqual },
  { label: ">", value: ZSurveyLogicConditionsOperator.enum.isGreaterThan },
  { label: "<", value: ZSurveyLogicConditionsOperator.enum.isLessThan },
  { label: ">=", value: ZSurveyLogicConditionsOperator.enum.isGreaterThanOrEqual },
  { label: "<=", value: ZSurveyLogicConditionsOperator.enum.isLessThanOrEqual },
];

const MULTI_SELECT = [
  OPT("does_not_include_one_of", "doesNotIncludeOneOf"),
  OPT("does_not_include_all_of", "doesNotIncludeAllOf"),
  OPT("includes_all_of", "includesAllOf"),
  OPT("includes_one_of", "includesOneOf"),
];

const SUBMISSION = [OPT("is_submitted", "isSubmitted"), OPT("is_skipped", "isSkipped")];

const PRESENCE = [OPT("is_set", "isSet"), OPT("is_not_set", "isNotSet")];

describe("getLogicRules", () => {
  describe("Question Specific Rules", () => {
    test("OpenText.text", () => {
      const openTextTextRules = elementRules[TSurveyQuestionTypeEnum.OpenText + ".text"];
      expect(openTextTextRules).toBeDefined();
      expect(openTextTextRules.options).toEqual([...TEXT_OPERATORS, ...SUBMISSION]);
    });

    test("OpenText.number", () => {
      const openTextNumberRules = elementRules[TSurveyQuestionTypeEnum.OpenText + ".number"];
      expect(openTextNumberRules).toBeDefined();
      expect(openTextNumberRules.options).toEqual([...NUMBER_COMPARISONS, ...SUBMISSION]);
    });

    test("MultipleChoiceSingle", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.MultipleChoiceSingle];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        ...EQUALITY,
        {
          label: "mockTranslate(workspace.surveys.edit.equals_one_of)",
          value: ZSurveyLogicConditionsOperator.enum.equalsOneOf,
        },
        ...SUBMISSION,
      ]);
    });

    test("MultipleChoiceMulti", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.MultipleChoiceMulti];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...EQUALITY, ...MULTI_SELECT, ...SUBMISSION]);
    });

    test("PictureSelection", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.PictureSelection];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...EQUALITY, ...MULTI_SELECT, ...SUBMISSION]);
    });

    test("Rating", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Rating];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...NUMBER_COMPARISONS, ...SUBMISSION]);
    });

    test("NPS", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.NPS];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...NUMBER_COMPARISONS, ...SUBMISSION]);
    });

    test("CTA", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.CTA];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        {
          label: "mockTranslate(workspace.surveys.edit.is_clicked)",
          value: ZSurveyLogicConditionsOperator.enum.isClicked,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_not_clicked)",
          value: ZSurveyLogicConditionsOperator.enum.isNotClicked,
        },
      ]);
    });

    test("Consent", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Consent];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        {
          label: "mockTranslate(workspace.surveys.edit.is_accepted)",
          value: ZSurveyLogicConditionsOperator.enum.isAccepted,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_skipped)",
          value: ZSurveyLogicConditionsOperator.enum.isSkipped,
        },
      ]);
    });

    test("Date", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Date];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        ...EQUALITY,
        {
          label: "mockTranslate(workspace.surveys.edit.is_before)",
          value: ZSurveyLogicConditionsOperator.enum.isBefore,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_after)",
          value: ZSurveyLogicConditionsOperator.enum.isAfter,
        },
        ...SUBMISSION,
      ]);
    });

    test("FileUpload", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.FileUpload];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...SUBMISSION]);
    });

    test("Signature words the pair as signed / not signed, on the same operators as File upload", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Signature];
      expect(rules.options).toEqual([OPT("is_signed", "isSubmitted"), OPT("is_not_signed", "isSkipped")]);
      // Same operators as File upload, only the words differ; File upload keeps submitted / skipped.
      expect(rules.options.map((option) => option.value)).toEqual(
        elementRules[TSurveyQuestionTypeEnum.FileUpload].options.map((option) => option.value)
      );
      expect(elementRules[TSurveyQuestionTypeEnum.FileUpload].options).toEqual(SUBMISSION);
    });

    test("Ranking", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Ranking];
      expect(rules).toBeDefined();
      // T21 (ENG-6937): "was ranked" compares the ranked options by id.
      expect(rules.options).toEqual([...MULTI_SELECT, ...SUBMISSION]);
    });

    test("Cal", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Cal];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        {
          label: "mockTranslate(workspace.surveys.edit.is_booked)",
          value: ZSurveyLogicConditionsOperator.enum.isBooked,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_skipped)",
          value: ZSurveyLogicConditionsOperator.enum.isSkipped,
        },
      ]);
    });

    test("Matrix", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Matrix];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        {
          label: "mockTranslate(workspace.surveys.edit.is_partially_submitted)",
          value: ZSurveyLogicConditionsOperator.enum.isPartiallySubmitted,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_completely_submitted)",
          value: ZSurveyLogicConditionsOperator.enum.isCompletelySubmitted,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_skipped)",
          value: ZSurveyLogicConditionsOperator.enum.isSkipped,
        },
      ]);
    });

    test("Matrix.row", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Matrix + ".row"];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([
        ...EQUALITY,
        {
          label: "mockTranslate(workspace.surveys.edit.is_empty)",
          value: ZSurveyLogicConditionsOperator.enum.isEmpty,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_not_empty)",
          value: ZSurveyLogicConditionsOperator.enum.isNotEmpty,
        },
        {
          label: "mockTranslate(workspace.surveys.edit.is_any_of)",
          value: ZSurveyLogicConditionsOperator.enum.isAnyOf,
        },
      ]);
    });

    test("Address", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.Address];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...SUBMISSION]);
    });

    test("ContactInfo", () => {
      const rules = elementRules[TSurveyQuestionTypeEnum.ContactInfo];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...SUBMISSION]);
    });
  });

  describe("Variable Specific Rules", () => {
    test("variable.text", () => {
      const rules = logicRules["variable.text"];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...TEXT_OPERATORS]);
    });

    test("variable.number", () => {
      const rules = logicRules["variable.number"];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...NUMBER_COMPARISONS]);
    });
  });

  // The list an ingested Embedded Data field inherits when it declares no narrower dataType — which
  // every field a legacy survey has does. Asserted in full because ENG-1853 retired the separate
  // `hiddenField` family in favour of this one, and "the operators did not change" is the claim.
  describe("Field Rules (string)", () => {
    test("field.string", () => {
      const rules = logicRules["field.string"];
      expect(rules).toBeDefined();
      expect(rules.options).toEqual([...TEXT_OPERATORS, ...PRESENCE]);
    });
  });
});

describe("dataType-keyed field rules (ENG-1840, ENG-1853)", () => {
  // Indexed explicitly rather than through a `Record<string, …>` cast: `getConditionOperatorOptions`
  // reaches these keys as `field.${dataType}` — for a reserved catalog entry and, since ENG-1853, for
  // an ingested Embedded Data field too — and naming all four here means deleting one is a compile
  // error in this test rather than a silently skipped loop iteration.
  const reservedRules = {
    string: logicRules["field.string"],
    number: logicRules["field.number"],
    boolean: logicRules["field.boolean"],
    date: logicRules["field.date"],
  };

  const dataTypes = Object.keys(reservedRules) as (keyof typeof reservedRules)[];

  const opValues = (dataType: keyof typeof reservedRules): string[] =>
    reservedRules[dataType].options.map((option) => option.value);

  test("there is a rule set for every embedded data type", () => {
    // `TEmbeddedDataType` is exactly these four, so a catalog entry can never index a missing family.
    expect(dataTypes.sort()).toStrictEqual(["boolean", "date", "number", "string"]);

    for (const dataType of dataTypes) {
      expect(opValues(dataType).length).toBeGreaterThan(0);
    }
  });

  test("every family can branch on absence", () => {
    // Such a value is legitimately absent (`source` on a link opened without one, an Embedded Data
    // field nothing filled), and isSet / isNotSet are the only operators that let an author handle
    // that.
    for (const dataType of dataTypes) {
      expect(opValues(dataType)).toEqual(
        expect.arrayContaining([
          ZSurveyLogicConditionsOperator.enum.isSet,
          ZSurveyLogicConditionsOperator.enum.isNotSet,
        ])
      );
    }
  });

  test("numbers get ordering, strings get substring matching", () => {
    expect(opValues("number")).toEqual(
      expect.arrayContaining([
        ZSurveyLogicConditionsOperator.enum.isGreaterThan,
        ZSurveyLogicConditionsOperator.enum.isLessThan,
      ])
    );
    expect(opValues("string")).toEqual(
      expect.arrayContaining([
        ZSurveyLogicConditionsOperator.enum.contains,
        ZSurveyLogicConditionsOperator.enum.startsWith,
      ])
    );
    expect(opValues("string")).not.toContain(ZSurveyLogicConditionsOperator.enum.isGreaterThan);
  });

  test("booleans offer equality only", () => {
    // They project as the strings "true"/"false", so ordering or substring operators would read
    // sensibly and never match.
    expect(opValues("boolean").sort()).toStrictEqual(
      [
        ZSurveyLogicConditionsOperator.enum.equals,
        ZSurveyLogicConditionsOperator.enum.doesNotEqual,
        ZSurveyLogicConditionsOperator.enum.isSet,
        ZSurveyLogicConditionsOperator.enum.isNotSet,
      ].sort()
    );
  });

  test("dates get chronological comparison", () => {
    expect(opValues("date")).toEqual(
      expect.arrayContaining([
        ZSurveyLogicConditionsOperator.enum.isBefore,
        ZSurveyLogicConditionsOperator.enum.isAfter,
      ])
    );
  });
});
