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

export default defineNuxtPlugin((nuxtApp) => {
  let token = useStorage("id_token", "GuestAccess").value;
  const config = useRuntimeConfig();

  const api = $fetch.create({
    baseURL: config.public.NUXT_PUBLIC_BASE_URL +
    config.public.NUXT_PUBLIC_API_NAME,
    
    onRequest({ request, options, error }) {
      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
    },
  });

  // Add custom methods for GET, POST, and DELETE
  const http = {
    getRequest: (url: string, options = {}) =>
      api(url, { method: "GET", ...options }),
    postRequest: (url: string, body: any, options = {}) =>
      api(url, { method: "POST", body, ...options }),
    deleteRequest: (url: string, options = {}) =>
      api(url, { method: "DELETE", ...options }),
  };

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