import log from "loglevel";

import { bustItGetCache, itGetCached, itPost } from "@/fetchHelpers";
import { useAppStore } from "@/stores/app";
import { defineStore } from "pinia";

const logoutRedirectUrl = import.meta.env.VITE_LOGOUT_REDIRECT;
// typed state https://stackoverflow.com/questions/71012513/when-using-pinia-and-typescript-how-do-you-use-an-action-to-set-the-state

export type UserState = {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  username: string;
  avatar_url: string;
  is_superuser: boolean;
  course_session_experts: number[];
  loggedIn: boolean;
};

const initialUserState: UserState = {
  id: 0,
  email: "",
  first_name: "",
  last_name: "",
  username: "",
  avatar_url: "",
  is_superuser: false,
  course_session_experts: [],
  loggedIn: false,
};

export const useUserStore = defineStore({
  id: "user",
  state: () => initialUserState as UserState,
  getters: {
    getFullName(): string {
      return `${this.first_name} ${this.last_name}`.trim();
    },
  },
  actions: {
    handleLogin(username: string, password: string, next = "/") {
      if (username && password) {
        itPost("/api/core/login/", {
          username,
          password,
        })
          .then((data) => {
            this.$state = data;
            this.loggedIn = true;
            log.debug("bust cache");
            bustItGetCache();
            log.debug(`redirect to ${next}`);
            window.location.href = next;
          })
          .catch(() => {
            this.loggedIn = false;
            alert("Login failed");
          });
      }
    },
    handleLogout() {
      Object.assign(this, initialUserState);

      itPost("/api/core/logout/", {}).then(() => {
        let redirectUrl;

        if (logoutRedirectUrl !== "") {
          redirectUrl = logoutRedirectUrl;
        } else {
          redirectUrl = "/";
        }
        window.location.href = redirectUrl;
      });
    },
    async fetchUser() {
      const appStore = useAppStore();
      const data = await itGetCached("/api/core/me/");
      this.$state = data;
      this.loggedIn = true;
      appStore.userLoaded = true;
    },
  },
});
