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

export const useCompletionStore = defineStore({
  id: "completion",
  state: () => {
    return {};
  },
  getters: {},
  actions: {
    async loadCourseSessionCompletionData(
      courseSessionId: string,
      userId: string,
      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: LearningContentWithCompletion | LearningUnitPerformanceCriteria,
      userId: string | undefined = undefined,
      courseSessionId: string | 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_id: page.id,
          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 [];
    },
  },
});
