const axios = require("axios");

const safeAxios = {
  async get(url, config = {}) {
    try {
      const { data } = await axios.get(url, config);
      return [null, data];
    } catch (err) {
      return [formatAxiosError(err), null];
    }
  },

  async post(url, payload = {}, config = {}) {
    try {
      const { data } = await axios.post(url, payload, config);
      return [null, data];
    } catch (err) {
      return [formatAxiosError(err), null];
    }
  },

  async put(url, payload = {}, config = {}) {
    try {
      const { data } = await axios.put(url, payload, config);
      return [null, data];
    } catch (err) {
      return [formatAxiosError(err), null];
    }
  },

  async delete(url, config = {}) {
    try {
      const { data } = await axios.delete(url, config);
      return [null, data];
    } catch (err) {
      return [formatAxiosError(err), null];
    }
  },
};

function formatAxiosError(error) {
  if (axios.isAxiosError(error)) {
    if (error.response) {
      return {
        status: error.response.status,
        message:
          error.response.data?.message ||
          error.response.statusText ||
          "Request failed.",
      };
    } else if (error.request) {
      return { status: 500, message: "No response from remote server." };
    } else {
      return { status: 500, message: error.message || "Axios error occurred" };
    }
  }
  return { status: 500, message: error?.message || error.toString() };
}

module.exports = safeAxios;
