import { itGet } from "@/fetchHelpers";
import type { MediaLibraryPage } from "@/types";
import log from "loglevel";
import { defineStore } from "pinia";

export type MediaLibraryStoreState = {
  mediaLibraryPage: MediaLibraryPage | undefined;
};

export const useMediaLibraryStore = defineStore({
  id: "mediaLibrary",
  state: () => {
    return {
      mediaLibraryPage: undefined,
    } as MediaLibraryStoreState;
  },
  getters: {},
  actions: {
    async loadMediaLibraryPage(slug: string, reload = false) {
      if (this.mediaLibraryPage && !reload) {
        return this.mediaLibraryPage;
      }
      log.debug("load mediaLibraryPageData");
      const mediaLibraryPageData = await itGet(`/api/course/page/${slug}/`);

      if (!mediaLibraryPageData) {
        throw `No mediaLibraryPageData found with: ${slug}`;
      }

      this.mediaLibraryPage = mediaLibraryPageData;
      return this.mediaLibraryPage;
    },
  },
});
