import { LevelExam, ListeningExam, ReadingExam, UserSolution } from "@/interfaces/exam";

// so that the compiler doesnt complain
interface Part {
  exercises: Array<{
    id: string;
    type: string;
    questions?: Array<any>;
    score?: { total: number };
  }>;
}

type PartExam = {
  parts: Part[];
} & (ReadingExam | ListeningExam | LevelExam)

const answeredEveryQuestionInPart = (exam: PartExam, partIndex: number, userSolutions: UserSolution[]) => {
  return exam.parts[partIndex].exercises.every((exercise) => {
    const userSolution = userSolutions.find(x => x.exercise === exercise.id);
    switch (exercise.type) {
      case 'multipleChoice':
        return userSolution?.solutions.length === exercise.questions!.length;
      case 'fillBlanks':
        return userSolution?.solutions.length === userSolution?.score.total;
      case 'writeBlanks':
        return userSolution?.solutions.length === userSolution?.score.total;
      case 'matchSentences':
        return userSolution?.solutions.length === userSolution?.score.total;
      case 'trueFalse':
        return userSolution?.solutions.length === userSolution?.score.total;
    }
    return false;
  });
}


const answeredEveryQuestion = (exam: PartExam, userSolutions: UserSolution[]) => {
  return exam.parts.every((_, index) => {
    return answeredEveryQuestionInPart(exam, index, userSolutions);
  });
}

export {
  answeredEveryQuestion,
  answeredEveryQuestionInPart
};
