export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig();

  const id_token = useCookie("id_token");
  const token = id_token.value ?? "GuestAccess";

  const baseUrl =
    config.public.NUXT_PUBLIC_BASE_URL + config.public.NUXT_PUBLIC_API_NAME;

  const api = $fetch.create({
    // baseURL: baseUrl,
    onRequest({ request, options, error }) {
      options.baseURL = baseUrl + options.baseURL;

      // options.baseURL = 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,
    },
  };
});
