import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
} from "axios";
import { toast } from "vue-sonner";

export function useApi() {
  const { $i18n } = useNuxtApp();
  const config = useRuntimeConfig();
  // Create Axios instance
  const apiClient: AxiosInstance = axios.create({
    baseURL: config.public.apiBase,
    headers: {
      "Content-Type": "application/json",
    },
    timeout: 60000,
  });

  // Request interceptor: add language header
  apiClient.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const locale = $i18n.locale.value;
      config.headers["Content-Language"] = locale === "en" ? "en" : "ar";

      return config;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  // Response interceptor: handle errors
  apiClient.interceptors.response.use(
    (response: AxiosResponse) => {
      return response;
    },
    (error) => {
      if (error?.response?.status === 500) {
        toast.error("Error", {
          description:
            error.response.data?.message || "An unexpected error occurred",
          class: `!text-white rounded-lg !text-[16px]`,
          style: {
            background: "linear-gradient(90deg, #112231 0%, #191A2E 100%)",
          },
        });
      } else {
        console.error(error.message);
      }

      return Promise.reject(error);
    },
  );

  return {
    get: async <T>(
      url: string,
      config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> => {
      const response = await apiClient.get<T>(url, config);
      return response;
    },
    post: async <T, D = unknown>(
      url: string,
      data: D,
      config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> => {
      const response = await apiClient.post<T>(url, data, config);
      return response;
    },
    patch: async <T, D = unknown>(
      url: string,
      data: D,
      config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> => {
      const response = await apiClient.patch<T>(url, data, config);
      return response;
    },
    put: async <T, D = unknown>(
      url: string,
      data: D,
      config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> => {
      const response = await apiClient.put<T>(url, data, config);
      return response;
    },
    delete: async <T>(
      url: string,
      config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> => {
      const response = await apiClient.delete<T>(url, config);
      return response;
    },
  };
}
