import { useAuthStore } from "~/stores/authStore";
import { useStorage } from "@vueuse/core";

// let lsToken = useStorage("token", "GuestAccess");
// if (lsToken == null || lsToken == "" || lsToken == undefined)
//   lsToken = "GuestAccess";

export default defineNuxtPlugin((nuxtApp) => {
  //   const { session } = useUserSession();
  // const authStore = useAuthStore();
  let token = useStorage("id_token", "GuestAccess").value;
  const api = $fetch.create({
    onRequest({ request, options, error }) {
      options.baseURL =
        import.meta.env.VITE_BASE_URL +
        import.meta.env.NUXT_PUBLIC_API_NAME+
        options.baseURL;

      if (token) {
        const headers = (options.headers ||= {});
        if (Array.isArray(headers)) {
          headers.push(["Authorization", token]);
        } else if (headers instanceof Headers) {
          headers.set("Authorization", token);
        } else {
          headers.Authorization = token;
        }
      }
    },
    async onResponseError({ response }) {
      if (response.status === 401) {
        await nuxtApp.runWithContext(() => navigateTo("/login"));
      }
    },
    onRequestError({ request, options, error }) {
      // Handle the request errors
    },
    onResponse({ request, response, options }) {
      // Process the response data
      // localStorage.setItem('token', response._data.token)
    },
  });

  // Expose to useNuxtApp().$api
  return {
    provide: {
      api,
    },
  };
});
