import type { FetchResponse } from "ofetch";
export const useApi: typeof useFetch = (url, opts = {}) => {
  const config = useRuntimeConfig();
  const token = useCookie("crm_token");

  interface ApiResponse {
    success: boolean;
    message: string;
    data?: any;
  }
  // carga inicial - acciones dinámicas
  return useFetch(url, {
    ...opts,
    baseURL: config.public.apiBase,
    headers: {
      Accept: "application/json",
      Authorization: token.value ? `Bearer ${token.value}` : "",
      ...opts.headers,
    },
    // Interceptores globales (opcional)
    onResponseError({ response }: { response: FetchResponse<ApiResponse> }) {
      const { swal } = useMessageSwal();
      swal.fire({
        title: "Ha ocurrido un error",
        text: response._data?.message,
        icon: "error",
      });
      if (response.status === 401) {
        token.value = null;
        navigateTo("/login");
      }
    },
  });
};

/*export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig();
  const token = useCookie("crm_token"); // Obtiene el token de la cookie
  const { swal } = useMessageSwal(); // Tu composable de alertas

  const $api = $fetch.create({
    baseURL: config.public.apiBase,

    // Se ejecuta ANTES de cada petición
    onRequest({ options }) {
      options.headers = {
        ...options.headers,
        Accept: "application/json",
        Authorization: token.value ? `Bearer ${token.value}` : "",
      };
    },

    // Se ejecuta si hay un ERROR (4xx o 5xx)
    onResponseError({ response }) {
      const mensaje = response._data?.message || "Ocurrió un error inesperado";

      // Muestra la alerta legible que configuramos en Laravel
      swal.fire({
        title: "Error",
        text: mensaje,
        icon: "error",
      });

      if (response.status === 401) {
        token.value = null;
        navigateTo("/login");
      }
    },
  });

  return {
    provide: {
      api: $api, // Lo registra como $api
    },
  };
});*/
