import { useRuntimeConfig } from "nuxt/app";
import type { ApiCallOptions, RequestBody } from "~/types/api";

export const useApi = () => {
  const config = useRuntimeConfig();
  const apiBase = config.public.baseUrl;

  const defaultHeaders = {
    Accept: "application/json",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
  };

  const apiCall = async <T>(
    endpoint: string,
    options: ApiCallOptions = {}
  ): Promise<T> => {
    options.retryCount = options.retryCount || 0;

    try {
      const headers: Record<string, string> = {
        ...defaultHeaders,
        ...options.headers,
      };

      return await $fetch<T>(endpoint, {
        baseURL: apiBase,
        method: options.method || "GET",
        headers,
        body: options.body,
      });
    } catch (error) {
      if (options.retryCount < 3) {
        options.retryCount++;
        return await apiCall<T>(endpoint, options);
      }
      console.error("Erro na API:", error);
      throw error;
    }
  };

  const get = <T>(endpoint: string, headers?: Record<string, string>) =>
    apiCall<T>(endpoint, { method: "GET", headers });

  const post = <T>(
    endpoint: string,
    body?: RequestBody,
    headers?: Record<string, string>
  ) => apiCall<T>(endpoint, { method: "POST", body, headers });

  const put = <T>(
    endpoint: string,
    body?: RequestBody,
    headers?: Record<string, string>
  ) => apiCall<T>(endpoint, { method: "PUT", body, headers });

  const del = <T>(endpoint: string, headers?: Record<string, string>) =>
    apiCall<T>(endpoint, { method: "DELETE", headers });

  const patch = <T>(
    endpoint: string,
    body?: RequestBody,
    headers?: Record<string, string>
  ) => apiCall<T>(endpoint, { method: "PATCH", body, headers });

  return { get, post, put, delete: del, patch };
};
