import type Config from '../../types/config';
import type GPTAnswer from '../../types/gpt-answer';
import type { SelectMissingWordResponse } from '../../types/question-types';
import { MoodleQuestionType } from '../../types/question-types';

export default function handleGapSelect(
  config: Config,
  inputList: NodeListOf<HTMLElement>,
  gptAnswer: GPTAnswer
): boolean {
  if (
    !gptAnswer.response ||
    gptAnswer.response.question_type !== MoodleQuestionType.SELECT_MISSING_WORD
  )
    return false;

  const response = gptAnswer.response as SelectMissingWordResponse;
  const selects = Array.from(inputList).filter(
    el => el.tagName === 'SELECT'
  ) as HTMLSelectElement[];

  for (const answer of response.correct_answers) {
    const selectEl = selects[answer.drop_down_index];
    if (!selectEl) continue;

    const options = selectEl.querySelectorAll('option');
    const correctOption = options[answer.option_index + 1];

    if (correctOption) {
      if (config.mouseover) {
        selectEl.addEventListener('click', () => (correctOption.selected = true), { once: true });
      } else {
        correctOption.selected = true;
      }
    }
  }

  return true;
}
