import { TResponseData } from "@formbricks/types/responses";
import { MAX_OTHER_OPTION_LENGTH } from "@/lib/constants";
import { getLocalizedValue } from "@/lib/i18n/utils";

type TQuestionWithOtherOptionValidation = {
  id: string;
  type: string;
  choices?: unknown[];
};

/**
 * Helper function to check if a string value is a valid "other" option
 * @returns BadRequestResponse if the value exceeds the limit, undefined otherwise
 */
export const validateOtherOptionLength = (
  value: string,
  choices: unknown[],
  questionId: string,
  language?: string
): string | undefined => {
  // Check if this is an "other" option (not in predefined choices)
  const matchingChoice = choices.find((choice) => {
    if (
      typeof choice !== "object" ||
      choice === null ||
      !("label" in choice) ||
      typeof choice.label !== "object" ||
      choice.label === null
    ) {
      return false;
    }
    const label = choice.label as Record<string, string>;
    const localizedLabel = getLocalizedValue(label, language ?? "default");
    // The survey renders the default label when a translation is blank, so that is what gets stored.
    const renderedLabel = localizedLabel.trim() ? localizedLabel : getLocalizedValue(label, "default");
    return renderedLabel === value;
  });

  // If this is an "other" option with value that's too long, reject the response
  if (!matchingChoice && value.length > MAX_OTHER_OPTION_LENGTH) {
    return questionId;
  }
};

export const validateOtherOptionLengthForMultipleChoice = ({
  responseData,
  surveyQuestions,
  responseLanguage,
}: {
  responseData?: TResponseData;
  surveyQuestions: TQuestionWithOtherOptionValidation[];
  responseLanguage?: string;
}): string | undefined => {
  if (!responseData) return undefined;
  for (const [questionId, answer] of Object.entries(responseData)) {
    const question = surveyQuestions.find((q) => q.id === questionId);
    if (!question) continue;

    // Ranking stores a ranked "Other" as free text in place of a label, like multiple choice.
    const hasOtherText =
      question.type === "multipleChoiceMulti" ||
      question.type === "multipleChoiceSingle" ||
      question.type === "ranking";

    if (!hasOtherText || !question.choices) continue;

    const error = validateAnswer(answer, question.choices, questionId, responseLanguage);
    if (error) return error;
  }

  return undefined;
};

function validateAnswer(
  answer: unknown,
  choices: unknown[],
  questionId: string,
  language?: string
): string | undefined {
  if (typeof answer === "string") {
    return validateOtherOptionLength(answer, choices, questionId, language);
  }

  if (Array.isArray(answer)) {
    for (const item of answer) {
      if (typeof item === "string") {
        const result = validateOtherOptionLength(item, choices, questionId, language);
        if (result) return result;
      }
    }
  }

  return undefined;
}
