// api.js

const API_URL = import.meta.env.VITE_API_URL;

// A helper function for making API requests
export const fetchData = async (endpoint) => {
  try {
    const response = await fetch(`${API_URL}/${endpoint}`);

    // Check if the response is actually JSON
    const text = await response.text();

    if (!response.ok) {
      throw new Error(`Error: ${response.statusText}`);
    }

    // Try parsing as JSON
    const data = JSON.parse(text);
    return data;
  } catch (error) {
    console.error("API request failed:", error.message);
    throw error;
  }
};

// Send data to the server
export const postData = async (endpoint, payload) => {
  try {
    const response = await fetch(`${API_URL}/${endpoint}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    const data = await response.json();
    if (!response.ok) {
      throw new Error(data.error || "Something went wrong");
    }

    return data;
  } catch (error) {
    console.error("API POST request failed:", error.message);
    throw error;
  }
};
