export const DEFAULT_SERVER_URL = "https://ruang.email";

let currentServerUrl = DEFAULT_SERVER_URL;

export const setServerUrl = (url) => {
  currentServerUrl = url ? url.replace(/\/+$/, "") : DEFAULT_SERVER_URL;
};

export const getServerUrl = () => currentServerUrl;

export const apiFetch = async (endpoint, options = {}) => {
  const base = getServerUrl();
  const url = endpoint.startsWith("http") ? endpoint : `${base}${endpoint.startsWith("/") ? "" : "/"}${endpoint}`;
  
  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    ...(options.headers || {}),
  };

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), options.timeout || 15000);

  try {
    const res = await fetch(url, {
      ...options,
      headers,
      signal: controller.signal,
    });
    clearTimeout(timeoutId);

    const data = await res.json();
    return data;
  } catch (err) {
    clearTimeout(timeoutId);
    if (err.name === "AbortError") {
      throw new Error("Permintaan waktu habis (timeout). Periksa koneksi internet Anda.");
    }
    throw err;
  }
};
