import { uniq } from 'lodash';
import {
  ReturnProcessAnswers,
  ReturnProcessQuestion,
  ReturnProcessQuestionKey,
} from '../../models';
import { ReturnProcessChecklistAnswerSchema } from '../../schemas';

export const getNextQuestion = (
  question: ReturnProcessQuestion,
  answers: ReturnProcessAnswers,
): ReturnProcessQuestionKey | undefined => {
  switch (question.type) {
    case 'select': {
      const option = question.options.find(
        (o) => o.value === answers[question.key],
      );
      return option?.nextQuestion;
    }
    case 'product':
      return answers[question.key] ? question.nextQuestion : undefined;
    case 'checklist': {
      const answer = ReturnProcessChecklistAnswerSchema.optional().parse(
        answers[question.key],
      );
      return (answer && answer.options?.length) || (answer && answer.other)
        ? question.nextQuestion
        : undefined;
    }
    case 'info':
      return question.nextQuestion;
    case 'group':
      return undefined; // Handle group questions separately
    default:
      console.warn('Implementation Missing for type:', question);
      return undefined;
  }
};

export const getAllNextQuestions = (
  question: ReturnProcessQuestion,
): ReturnProcessQuestionKey[] | undefined => {
  switch (question.type) {
    case 'select': {
      return uniq(
        question.options
          .map((o) => o.nextQuestion)
          .filter(Boolean) as ReturnProcessQuestionKey[],
      );
    }
    case 'product':
      return [question.nextQuestion].filter(
        Boolean,
      ) as ReturnProcessQuestionKey[];
    case 'checklist':
      return [question.nextQuestion].filter(
        Boolean,
      ) as ReturnProcessQuestionKey[];
    case 'info':
      return [question.nextQuestion].filter(
        Boolean,
      ) as ReturnProcessQuestionKey[];
    case 'group':
      return undefined; // Handle group questions separately
    default:
      console.warn('Implementation Missing for type:', question);
      return undefined;
  }
};
