import { authApi, customerApi, managerApi } from "@/api/api";
import { loadCart, loadWishlist } from "@/store/index";

export let authLoaded = false;

export const onAuthGuard = async () => {
  try {
    let accessToken = "";
    authLoaded = false;
    const response = await authApi.post(
      "/customer/accessToken",
      {},
      { withCredentials: true }
    );
    console.log("response.data.accessToken", response.data.accessToken);
    if (response.data.accessToken) {
      accessToken = response.data.accessToken;
      setAccountData(response.data);
    }
    await customerApi.interceptors.request.use(
      (config) => {
        if (accessToken) {
          config.headers["Authorization"] = "Bearer " + accessToken;
        }
        config.withCredentials = true;
        return config;
      },
      (error) => {
        Promise.reject(error);
      }
    );
    await authApi.interceptors.request.use(
      (config) => {
        if (accessToken) {
          config.headers["Authorization"] = "Bearer " + accessToken;
        }
        config.withCredentials = true;
        return config;
      },
      (error) => {
        Promise.reject(error);
      }
    );
    await managerApi.interceptors.request.use(
      (config) => {
        if (accessToken) {
          config.headers["Authorization"] = "Bearer " + accessToken;
        }
        config.withCredentials = true;
        return config;
      },
      (error) => {
        Promise.reject(error);
      }
    );
    loadCart();
    loadWishlist();
    authLoaded = true;
  } catch (err) {
    loadCart();
    loadWishlist();
    authLoaded = true;
    console.log(err);
  }
};
