import { bustItGetCache, itGetCached, itPost } from "@/fetchHelpers";
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 loadCompletionData(courseId: number, userId: number, reload = false) {
      const userCompletionData = (await itGetCached(
        `/api/course/completion/${courseId}/${userId}/`,
        {
          reload: reload,
        }
      )) as CourseCompletion[];

      if (userCompletionData === undefined) {
        throw `No completionData found with: ${courseId}, ${userId}`;
      }
      return userCompletionData || [];
    },
    async markPage(
      page: BaseCourseWagtailPage,
      userId: number | undefined = undefined
    ) {
      const completionData = await itPost("/api/course/completion/mark/", {
        page_key: page.translation_key,
        completion_status: page.completion_status,
      });

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

      return completionData as CourseCompletion[];
    },
  },
});
