import ky, { AfterResponseHook, NormalizedOptions } from "ky";
import { computed, ref } from "vue";
import { errorToast } from "../utils/composables/use-toast";
export { VueQueryPlugin } from "@tanstack/vue-query";

export const token = ref<string | null>(localStorage.getItem("token_studio"));

// @ts-ignore
export const apiUrl = import.meta.env.VITE_API_URL;

export const setToken = (_token: string) => {
  localStorage.setItem("token_studio", _token);
  token.value = _token;
};

export const logout = () => {
  localStorage.removeItem("token_studio");
  token.value = null;
  window.location.reload();
};

export const isLoggedIn = computed(() => {
  return !!token.value;
});

const headersInterceptor = (options: Request) => {
  if (token.value) {
    options.headers.set("Authorization", `Bearer ${token.value}`);
  }
};

const errorInterceptor: AfterResponseHook = async (
  request: Request,
  _options: NormalizedOptions,
  response: Response
) => {
  const body: any = await response.json();

  if (body.message === "Token expired") {
    logout();
    return;
  }

  if (body.message && response.status >= 400) {
    errorToast({
      message: body.message,
    });
  }

  if (response.status >= 400) {
    throw { data: body };
  }
};

const kyInstance = ky.create({
  // @ts-ignore
  prefixUrl: import.meta.env.VITE_API_URL,
  hooks: {
    beforeRequest: [headersInterceptor],
    afterResponse: [errorInterceptor],
  },
});

const responseBody = async (response: any) => {
  return await response.json();
};

export const requests = {
  get: async (url: string, _options: any = {}) =>
    await kyInstance.get(url, _options).then(responseBody),
  post: async (url: string, body: any, _options = {}) =>
    await kyInstance
      .post(url, {
        json: body,
        ..._options,
      })
      .then(responseBody),
  put: async (url: string, body: any, _options: any = {}) =>
    await kyInstance
      .put(url, {
        json: body,
        ..._options,
      })
      .then(responseBody),
  delete: async (url: string, _options: any = {}) =>
    await kyInstance.delete(url, _options).then(responseBody),
  postMultipart: async (url: string, body: any, _options: any = {}) =>
    await kyInstance
      .post(url, {
        body: body,
        ..._options,
        timeout: 2147483647,
      })
      .then(responseBody),
};

export const useToken = () => {
  return {
    token,
    setToken,
    isLoggedIn,
    logout,
  };
};
