import { itGetCached } from "@/fetchHelpers";
import { LearningPath } from "@/services/learningPath";
import { useCompletionStore } from "@/stores/completion";
import { useUserStore } from "@/stores/user";
import _ from "lodash";
import { defineStore } from "pinia";

export type LearningPathStoreState = {
  learningPaths: Map<string, LearningPath>;

  page: "INDEX" | "OVERVIEW";
};

export const useLearningPathStore = defineStore({
  id: "learningPath",
  state: () => {
    return {
      learningPaths: new Map<string, LearningPath>(),
      page: "INDEX",
      loading: false,
    } as LearningPathStoreState;
  },
  getters: {
    learningPathForUser: (state) => {
      return (courseSlug: string, userId: number | string) => {
        if (state.learningPaths.size > 0) {
          const learningPathKey = `${courseSlug}-lp-${userId}`;
          return state.learningPaths.get(learningPathKey);
        }

        return undefined;
      };
    },
  },
  actions: {
    async loadLearningPath(
      slug: string,
      userId: number | undefined = undefined,
      reload = false,
      fail = true
    ) {
      if (!userId) {
        const userStore = useUserStore();
        userId = userStore.id;
      }

      const key = `${slug}-${userId}`;

      if (this.learningPaths.has(key) && !reload) {
        return this.learningPaths.get(key);
      }

      const learningPathData = await itGetCached(`/api/course/page/${slug}/`);
      if (!learningPathData && fail) {
        throw `No learning path found with: ${slug}`;
      }

      const completionStore = useCompletionStore();
      const completionData = await completionStore.loadCompletionData(
        learningPathData.course.id,
        userId
      );

      const learningPath = LearningPath.fromJson(
        _.cloneDeep(learningPathData),
        completionData
      );
      this.learningPaths.set(key, learningPath);
      return learningPath;
    },
  },
});
