// @ts-nocheck
import router from "../../router";
import Vue from "vue";
import axios from "axios";
import { axiosCacheInstance } from "@/plugins/axios";

const state = {};

const mutation = {};

// @ts-ignore
// @ts-ignore
const actions = {
  /**
   * login the user.
   * @param {*} context
   * @param {*} param1
   */
  // @ts-ignore
  async login(context, { email, password, driver, profile }) {
    let res;
    try {
      if (driver === "google") {
        res = await axios.post("/api/login/google/callback", {
          profile,
        });
      } else if (driver === "facebook") {
        res = await axios.post("/api/login/facebook/callback", {
          profile,
        });
        if (res.data.message === "email required") {
          // if email was not provide by the OAuth provider
          await router.push({
            name: "complete_signup",
            params: { profile: profile, driver: driver },
          });
          return;
        }
      } else {
        res = await axios.post("/api/login", {
          email: email,
          password: password,
        });
      }
      if (res) {
        const token = res.data["access_token"];
        if (token) {
          context.commit("setToken", token);
          // save the token at local storage if it exists
          localStorage.setItem("token", token);
          axios.defaults.headers.common["Authorization"] =
            axiosCacheInstance.defaults.headers.common["Authorization"] =
              "Bearer " + token;
          await context.dispatch("fetchUser");

          const user = context.getters.getUser;
          if (user) {
            var isArtist = user.roles
              ? user.roles.some(
                  (role: { name: string }) => role.name === "artist"
                ) || user.is_admin
              : false;
            var isAdmin = user.roles
              ? user.roles.some(
                  (role: { name: string }) => role.name === "admin"
                )
              : false;
          }
          if (isAdmin) {
            await router.push({
              name: "admin.analytics",
            });
          } else if (isArtist) {
            await router.push({
              name: "artist.analytics",
            });
          } else {
            await router.push({
              path: "home",
            });
          }

          if (
            context.getters.getSettings.ga4 &&
            context.getters.getSettings.analytics_login_event
          ) {
            emitAnalyticsEvent({
              action: "login",
              category: "auth",
              label: context.getters.getUser.email,
            });
          }
          return Promise.resolve();
        } else {
          Vue.notify({
            type: "error",
            group: "foo",
            message: "Authentification failed try again!",
          });
        }
      }
    } catch (e) {
      throw e;
    }
  },
  /**
   * Logout the user.
   * @param {*} context
   */
  // @ts-ignore
  async logout(context) {
    const res = await axios.post("/api/logout");
    if (context.state.fbLogoutFunction) {
      context.state.fbLogoutFunction();
    }
    if (res.status == 200) {
      if (
        context.getters.getSettings.ga4 &&
        context.getters.getSettings.analytics_logout_event
      ) {
        emitAnalyticsEvent({
          action: "logout",
          category: "auth",
          label: context.getters.getUser.email,
        });
      }
      context.commit("setUser", null);
      localStorage.removeItem("token");
    }
    window.open("/login", "_self");
  },
};

export default {
  state,
  mutation,
  actions,
};
