import { bustItGetCache, itGetCached, itPost } from "@/fetchHelpers";
import { useCourseSessionsStore } from "@/stores/courseSessions";
import { useUserStore } from "@/stores/user";
import type { BaseCourseWagtailPage, CourseCompletion } from "@/types";
import { defineStore } from "pinia";

export const useCompletionStore = defineStore({
  id: "completion",
  state: () => {
    return {};
  },
  getters: {},
  actions: {
    async loadCourseSessionCompletionData(
      courseSessionId: number,
      userId: number,
      reload = false
    ) {
      const userCompletionData = (await itGetCached(
        `/api/course/completion/${courseSessionId}/${userId}/`,
        {
          reload: reload,
        }
      )) as CourseCompletion[];

      if (userCompletionData === undefined) {
        throw `No completionData found with: ${courseSessionId}, ${userId}`;
      }
      return userCompletionData || [];
    },
    async markPage(
      page: BaseCourseWagtailPage,
      userId: number | undefined = undefined,
      courseSessionId: number | undefined = undefined
    ) {
      if (!courseSessionId) {
        const courseSessionsStore = useCourseSessionsStore();
        const courseSession = courseSessionsStore.currentCourseSession;
        if (courseSession) {
          courseSessionId = courseSession.id;
        }
      }

      if (courseSessionId) {
        const completionData = await itPost("/api/course/completion/mark/", {
          page_key: page.translation_key,
          completion_status: page.completion_status,
          course_session_id: courseSessionId,
        });

        if (completionData && completionData.length > 0) {
          if (!userId) {
            const userStore = useUserStore();
            userId = userStore.id;
          }
          bustItGetCache(`/api/course/completion/${courseSessionId}/${userId}/`);
        }

        return completionData as CourseCompletion[];
      }

      return [];
    },
  },
});
