import { myToast } from "./toastify";

export const fetchWeather = async (city: string, units: string) => {
  try {
    const response = await fetch(
      `https://weather.the1s.de/backend/api/fetchWeather?city=${encodeURIComponent(
        city
      )}&units=${encodeURIComponent(units)}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    const responseData = await response.json();

    if (!response.ok) {
      myToast(responseData.error, "error");
      return;
    }
    localStorage.setItem("weather", JSON.stringify(responseData.data));
    myToast(responseData.success, "success");
    return;
  } catch (error) {
    const errorMsg = JSON.stringify(error);
    myToast(errorMsg, "error");
    return null;
  }
};
