import { sleep } from "../../util";
import { getStoreName } from "../../util/survey-utils/page-info";
import { Survey, TAnswerMethod } from "../../util/survey-utils/survey";
import { VITAL_FARMS_QUESTIONS } from "./questions";
import { STORE_ANSWERS } from "./store-answers";
import { TQuestionType } from "./types";

const QUESTION_TYPE_TO_ANSWER_METHOD: Record<TQuestionType, TAnswerMethod> = {
  text: "input",
  radio: "radio",
  checkbox: "checkbox",
};

export async function fillVitalFarms(): Promise<void> {
  const survey = Survey.getInstance();
  const storeName = getStoreName().toUpperCase();

  const storeAnswers = STORE_ANSWERS[storeName];
  if (storeAnswers === undefined) {
    throw new Error(`[fillVitalFarms] No configured answers for store '${storeName}'`);
  }

  for (const [key, question] of Object.entries(VITAL_FARMS_QUESTIONS)) {
    const answer = storeAnswers[key];
    if (answer === undefined) {
      console.warn(`No configured answer for '${key}' (store '${storeName}'). Skipping.`);
      continue;
    }

    const method = QUESTION_TYPE_TO_ANSWER_METHOD[question.questionType];

    try {
      if (Array.isArray(answer)) {
        for (const value of answer) {
          survey.answer(method, question.questionLabel, value);
          await sleep(10);
        }
        continue;
      }

      survey.answer(method, question.questionLabel, answer);
    } catch (error) {
      console.error(error);
      continue;
    }

    await sleep(10);
  }
}
