const API_URL = window.__ENV__?.API_BASE || window.ENV?.VITE_API_URL || "http://192.168.1.100:8000";

// Get auth token from localStorage
const getAuthHeaders = () => {
  const token = localStorage.getItem("auth_token");
  return {
    "Content-Type": "application/json",
    ...(token && { Authorization: `Bearer ${token}` }),
  };
};

// Get all grocery lists
export const getGroceryLists = async () => {
  const res = await fetch(`${API_URL}/grocery-lists`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error("Failed to fetch grocery lists");
  return res.json();
};

// Create a new grocery list
export const createGroceryList = async (data) => {
  const res = await fetch(`${API_URL}/grocery-lists`, {
    method: "POST",
    headers: getAuthHeaders(),
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to create grocery list");
  }
  return res.json();
};

// Get a specific grocery list
export const getGroceryList = async (id) => {
  const res = await fetch(`${API_URL}/grocery-lists/${id}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error("Failed to fetch grocery list");
  return res.json();
};

// Update a grocery list
export const updateGroceryList = async (id, data) => {
  const res = await fetch(`${API_URL}/grocery-lists/${id}`, {
    method: "PUT",
    headers: getAuthHeaders(),
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to update grocery list");
  }
  return res.json();
};

// Delete a grocery list
export const deleteGroceryList = async (id) => {
  const res = await fetch(`${API_URL}/grocery-lists/${id}`, {
    method: "DELETE",
    headers: getAuthHeaders(),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to delete grocery list");
  }
};

// Toggle pin status for a grocery list
export const togglePinGroceryList = async (id) => {
  const res = await fetch(`${API_URL}/grocery-lists/${id}/pin`, {
    method: "PATCH",
    headers: getAuthHeaders(),
  });
  if (!res.ok) {
    let errorMessage = "Failed to toggle pin status";
    try {
      const error = await res.json();
      errorMessage = error.detail || errorMessage;
    } catch (e) {
      errorMessage = `HTTP ${res.status}: ${res.statusText}`;
    }
    throw new Error(errorMessage);
  }
  return res.json();
};

// Share a grocery list
export const shareGroceryList = async (listId, data) => {
  const res = await fetch(`${API_URL}/grocery-lists/${listId}/share`, {
    method: "POST",
    headers: getAuthHeaders(),
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to share grocery list");
  }
  return res.json();
};

// Get grocery list shares
export const getGroceryListShares = async (listId) => {
  const res = await fetch(`${API_URL}/grocery-lists/${listId}/shares`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error("Failed to fetch shares");
  return res.json();
};

// Unshare a grocery list
export const unshareGroceryList = async (listId, userId) => {
  const res = await fetch(`${API_URL}/grocery-lists/${listId}/shares/${userId}`, {
    method: "DELETE",
    headers: getAuthHeaders(),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to unshare grocery list");
  }
};

// Update share permissions
export const updateSharePermission = async (listId, userId, canEdit) => {
  const res = await fetch(`${API_URL}/grocery-lists/${listId}/shares/${userId}`, {
    method: "PATCH",
    headers: getAuthHeaders(),
    body: JSON.stringify({ can_edit: canEdit }),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to update share permission");
  }
  return res.json();
};

// Search users
export const searchUsers = async (query) => {
  const res = await fetch(`${API_URL}/users/search?q=${encodeURIComponent(query)}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error("Failed to search users");
  return res.json();
};
