import { create } from "zustand";
import { devtools } from "zustand/middleware";

type Answer = {
  questionId: string;
  answer: string;
};

interface QuizViewStore {
  answers: Answer[];
}

export const useQuizViewStore = create<QuizViewStore>()(
  devtools(
    (set, get) => ({
      answers: [],
    }),
    {
      name: "quizView",
    }
  )
);

export const updateAnswer = (questionId: string, answer: string) => {
  const answers = [...useQuizViewStore.getState().answers];
  const answerIndex = answers.findIndex((answer) => questionId === answer.questionId);

  if (answerIndex < 0) {
    answers.push({ questionId, answer });
  } else {
    answers[answerIndex] = { questionId, answer };
  }

  useQuizViewStore.setState({ answers });
};

export const getAnswersByQuestionId = (questionId: string) => {
  if (questionId === null) return null;
  const answers = [...useQuizViewStore.getState().answers];
  return answers.find(a => a.questionId === questionId) || null;
}