// Get API base from injected env.js or fallback to /api relative path
export const getApiBase = () => {
  if (typeof window !== "undefined" && window.__ENV__ && window.__ENV__.API_BASE) {
    return window.__ENV__.API_BASE;
  }
  // Default to relative /api path for local/containerized deployments
  return "/api";
};

const API_BASE = getApiBase();

export async function getRecipes() {
  const res = await fetch(`${API_BASE}/recipes`);
  if (!res.ok) {
    throw new Error("Failed to fetch recipes");
  }
  return res.json();
}

export async function getRandomRecipe(filters) {
  const params = new URLSearchParams();
  if (filters.mealType) params.append("meal_type", filters.mealType);
  if (filters.maxTime) params.append("max_time", filters.maxTime);

  if (filters.ingredients && filters.ingredients.length > 0) {
    filters.ingredients.forEach((ing) => {
      params.append("ingredients", ing);
    });
  }

  const queryString = params.toString();
  const url = queryString ? `${API_BASE}/recipes/random?${queryString}` : `${API_BASE}/recipes/random`;
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error("Failed to fetch random recipe");
  }
  return res.json();
}

export async function createRecipe(recipe, token) {
  const headers = { "Content-Type": "application/json" };
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  const res = await fetch(`${API_BASE}/recipes`, {
    method: "POST",
    headers,
    body: JSON.stringify(recipe),
  });
  if (!res.ok) {
    throw new Error("Failed to create recipe");
  }
  return res.json();
}

export async function updateRecipe(id, payload, token) {
  const headers = { "Content-Type": "application/json" };
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  const res = await fetch(`${API_BASE}/recipes/${id}`, {
    method: "PUT",
    headers,
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    throw new Error("Failed to update recipe");
  }
  return res.json();
}

export async function deleteRecipe(id, token) {
  const headers = {};
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  const res = await fetch(`${API_BASE}/recipes/${id}`, {
    method: "DELETE",
    headers,
  });
  if (!res.ok && res.status !== 204) {
    throw new Error("Failed to delete recipe");
  }
}