import axios from "axios";

export default {
  getFruits: async ({ commit }) => {
    await axios
      .get("http://localhost:3000/fruit")
      .then(res => {
        commit("setFruits", res.data.data);
      })
      .catch(err => {
        if (err.message === "Network Error") throw "Check API connectivity ...";
      })
      .finally(() => commit("setLoading", false));
  },
  getFruit: async ({ commit }, id) => {
    await axios.get(`http://localhost:3000/fruit/${id}`).then(res => commit("setFruit", res.data));
  },
  addFruit: async ({ commit }, fruit) => {
    commit("setLoading", true);
    await axios
      .post("http://localhost:3000/fruit", fruit)
      .then(res => commit("addFruit", res.data))
      .catch(err => {
        throw new Error(err.message);
      })
      .finally(() => commit("setLoading", false));
  },
  removeFruit: async ({ commit }, id) => {
    await axios
      .delete(`http://localhost:3000/fruit/${id}`)
      .then(() => {
        commit("removeFruit", id);
        commit("toggleDeleteMode");
      })
      .catch(err => {
        throw new Error(err.message);
      });
  },
  getImageFromUnsplash: async ({ commit }, keyword) => {
    commit("setLoading", true);
    return await axios
      .get(`https://api.unsplash.com/search/photos?query=${keyword}&w=800&h=400`, {
        headers: {
          Authorization: "Client-ID NjFwGYsnksnzH2uh12W55aobUpTe0h06oSVACd5cWt0",
          "X-Total": 1
        }
      })
      .then(res => {
        if (res.data.total === 0) throw new Error("0 found.");
        return res.data.results[0];
      })
      .finally(() => commit("setLoading", false));
  }
};
