<script lang="ts" context="module">
  import {
    CheckIfAniListLoggedIn,
    GetAniListLoggedInUser,
    GetAniListUserWatchingList,
  } from "../../wailsjs/go/main/App";
  import {
    aniListUser,
    watchListPage,
    animePerPage,
    aniListPrimary,
    aniListLoggedIn,
    aniListWatchlist,
    aniListSort,
    clearApiError,
    setApiError,
    serviceLoggingIn,
  } from "./GlobalVariablesAndHelperFunctions.svelte";

  let isAniListPrimary: boolean;
  let page: number;
  let perPage: number;
  let sort: string;

  aniListPrimary.subscribe((value) => (isAniListPrimary = value));
  watchListPage.subscribe((value) => (page = value));
  animePerPage.subscribe((value) => (perPage = value));
  aniListSort.subscribe((value) => (sort = value));

  export const LoadAniListUser = async () => {
    try {
      await GetAniListLoggedInUser().then((user) => {
        aniListUser.set(user);
      });
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      setApiError(
        "anilist",
        `Failed to load user: ${errorMsg}`,
        undefined,
        true,
      );
      throw err;
    }
  };

  export const LoadAniListWatchList = async () => {
    try {
      const watchList = await GetAniListUserWatchingList(page, perPage, sort);
      aniListWatchlist.set(watchList);
      clearApiError();
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      setApiError(
        "anilist",
        `Failed to load watch list: ${errorMsg}`,
        undefined,
        true,
      );
      throw err;
    }
  };
  export const CheckIfAniListLoggedInAndLoadWatchList = async () => {
    serviceLoggingIn.update((s) => [...s, "anilist"]);
    try {
      const loggedIn = await CheckIfAniListLoggedIn();
      if (loggedIn) {
        await LoadAniListUser();
        if (isAniListPrimary) await LoadAniListWatchList();
      }
      aniListLoggedIn.set(loggedIn);
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      setApiError(
        "anilist",
        `Authentication failed: ${errorMsg}`,
        undefined,
        true,
      );
      aniListLoggedIn.set(false);
    } finally {
      serviceLoggingIn.update((s) => s.filter((item) => item !== "anilist"));
    }
  };
</script>
