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

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

  const response = gptAnswer.response as OrderingResponse;

  // The sortable list is present within inputList because we added .sortablelist to code-listener.ts
  const sortableList = Array.from(inputList).find(el => el.classList.contains('sortablelist'));
  if (!sortableList) return true;

  const container = sortableList.closest('.que');
  if (!container) return true;

  const items = Array.from(sortableList.querySelectorAll('li.sortableitem'));

  // Form final array of element IDs to place in hidden input
  const correctIdsList: string[] = [];
  const orderedItems: HTMLElement[] = [];

  for (const index of response.correct_order.indexes) {
    const item = items[index] as HTMLElement;
    if (!item) continue;
    correctIdsList.push(item.id);
    orderedItems.push(item);
  }

  // Find the hidden input
  const hiddenInput = container.querySelector(
    'input[type="hidden"][name*="_response_"]'
  ) as HTMLInputElement;
  if (hiddenInput) {
    hiddenInput.value = correctIdsList.join(',');
  }

  // Visually reorder elements in DOM if mouseover auto-completion is disabled (meaning auto populate directly)
  // Even if mouseover is enabled, moodle drag/drop handles are too complex to easily simulate,
  // so typically visual repopulation on ordering is acceptable.
  orderedItems.forEach(item => {
    sortableList.appendChild(item); // appendChild physically moves an already existing dom element
  });

  return true;
}
