// Single source of truth for backend communication

const BASE_URL = import.meta.env.VITE_API_URL || "";

export const api = {
  post: async (path, body) => {
    // Make sure we form the correct full URL (handling missing slashes if any)
    const url = path.startsWith("http") ? path : `${BASE_URL}${path}`;

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    let data;
    let textResult = await response.text();
    try {
      data = textResult ? JSON.parse(textResult) : {};
    } catch (e) {
      data = { detail: "Backend Server is Unreachable (Proxy Error: " + response.status + ")" };
    }

    if (!response.ok) {
      // FastAPI typically throws Error messages under `detail`
      let errMsg = "An error occurred during communication";

      if (typeof data.detail === "string") {
        errMsg = data.detail;
      } else if (Array.isArray(data.detail)) {
        // FastAPI validation errors
        errMsg = data.detail.map(d => d.msg).join(", ");
      } else if (data.message) {
        errMsg = data.message;
      }

      throw new Error(errMsg);
    }

    return data;
  },
};
