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

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

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

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

    const options = selectEl.querySelectorAll('option');
    const correctOption = options[answer.option_index + 1]; // + 1 because index 0 is "Choose..."

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

  return true;
}
