import { Module } from "vuex";
import { RootState } from "../index";
import { ApiException, User } from "ChillMainAssets/types";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

export interface State {
  currentUser: User | null;
}

export const moduleUser: Module<State, RootState> = {
  state: () => ({
    currentUser: null,
  }),

  getters: {
    currentUser(state) {
      return state.currentUser;
    },
  },

  mutations: {
    setCurrentUser(state, user: User) {
      state.currentUser = user;
    },
  },

  actions: {
    async getCurrentUser({ commit }) {
      try {
        const userData: User = await makeFetch(
          "GET",
          "/api/1.0/main/whoami.json",
        );
        commit("setCurrentUser", userData);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
