import type { NitroFetchOptions } from "nitropack";

export const useHttp = async <T>(
  url: string,
  options: NitroFetchOptions<string> = {}
): Promise<T> => {

  const config = useRuntimeConfig();
  const token = useCookie("crm_token");

  try {
    return await $fetch<T>(url, {
      baseURL: config.public.apiBase,
      ...options,
      headers: {
        Accept: "application/json",

        Authorization: token.value
          ? `Bearer ${token.value}`
          : "",
        ...options.headers,
      },
    });

  } catch (err: any) {
    const { swal } = useMessageSwal();
    swal.fire({
      title: "Ha ocurrido un error",
      text:
        err?.data?.message ||
        "Error interno del servidor",
      icon: "error",
    });

    if (err?.status === 401) {
      token.value = null;
      await navigateTo("/login");
    }
    throw err;
  }
};
