// stores/useExamConfigStore.ts
import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { StartExamPayload, ExamMode } from "../types/test";

type UserMetrics = {
  xp: number;
  questions: number;
  streak: number;
};

interface ExamConfigState {
  payload: StartExamPayload | null;
  userMetrics: UserMetrics;

  setSheetId: (id: string) => void;
  storeTopics: (ids: string[]) => void;
  setDifficulty: (difficulty: StartExamPayload["difficulty"]) => void;

  setQuestionCount: (count: number) => void;
  storeDuration: (minutes: number) => void;
  setMode: (mode: ExamMode) => void;
  setSection: (section: string) => void;
  setUserMetrics: (userMetrics: UserMetrics) => void;

  clearPayload: () => void;
}

export const useExamConfigStore = create<ExamConfigState>()(
  persist(
    (set, get) => ({
      payload: null,
      userMetrics: {
        xp: 0,
        questions: 0,
        streak: 0,
      },

      setSheetId: (sheet_id) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            sheet_id,
          } as StartExamPayload,
        }),

      storeTopics: (topic_ids) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            topic_ids,
          } as StartExamPayload,
        }),
      setSection: (section) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            section,
          } as StartExamPayload,
        }),
      setUserMetrics: (userMetrics) =>
        set({
          userMetrics: userMetrics,
        }),

      setDifficulty: (difficulty) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            difficulty,
          } as StartExamPayload,
        }),

      setQuestionCount: (question_count) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            question_count,
          } as StartExamPayload,
        }),

      storeDuration: (time_limit_minutes) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            time_limit_minutes,
          } as StartExamPayload,
        }),

      setMode: (mode) =>
        set({
          payload: {
            ...(get().payload ?? {}),
            mode,
          } as StartExamPayload,
        }),

      clearPayload: () => set({ payload: null }),
    }),
    {
      name: "exam-config-storage",
    },
  ),
);
