import axios, { AxiosRequestConfig } from 'axios';

import { GATEWAY_API_URL } from '@/config-global';

// ----------------------------------------------------------------------

const axiosInstance = axios.create({ baseURL: GATEWAY_API_URL });

axiosInstance.interceptors.response.use(
  (res) => res,
  (error) => Promise.reject((error.response && error.response.data) || 'Something went wrong')
);

export default axiosInstance;

// ----------------------------------------------------------------------
export const fetcher = async (
  args: string | [string, AxiosRequestConfig],
  method: 'get' | 'post' | 'put' | 'delete' | 'patch',
  data?: any
) => {
  try {
    const [url, config] = Array.isArray(args) ? args : [args];
    const axiosConfig = { ...config, method };

    if (method === 'post' || method === 'put' || method === 'patch') {
      axiosConfig.data = data;
    }
    const res = await axiosInstance(url, axiosConfig);

    return res.data;
  } catch (error) {
    console.error('Failed to fetch:', error);
    throw error;
  }
};
