/** API client for Dostalgia backend. */

const BASE = import.meta.env.PROD ? "" : "";  // Proxy handles it in dev

async function request(path, options = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { "Content-Type": "application/json", ...options.headers },
    ...options,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || `HTTP ${res.status}`);
  }
  return res.json();
}

/** Fetch game list */
export async function listGames(params = {}) {
  const qs = new URLSearchParams();
  if (params.search) qs.set("search", params.search);
  if (params.genre) qs.set("genre", params.genre);
  if (params.limit) qs.set("limit", params.limit);
  if (params.offset) qs.set("offset", params.offset);
  return request(`/api/games?${qs}`);
}

/** Fetch single game */
export async function getGame(id) {
  return request(`/api/games/${id}`);
}

/** Update game metadata */
export async function updateGame(id, data) {
  return request(`/api/games/${id}`, {
    method: "PATCH",
    body: JSON.stringify(data),
  });
}

/** Delete a game */
export async function deleteGame(id) {
  return request(`/api/games/${id}`, { method: "DELETE" });
}

/** Upload a game ZIP */
export async function uploadGame(file, title) {
  const form = new FormData();
  form.append("file", file);
  if (title) form.append("title", title);

  const res = await fetch(`${BASE}/api/upload`, {
    method: "POST",
    body: form,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || `HTTP ${res.status}`);
  }
  return res.json();
}

/** Search IGDB (placeholder) */
export async function searchIGDB(query) {
  return request(`/api/igdb/search?query=${encodeURIComponent(query)}`);
}

/** Get artwork URL for a path — returns proxy URL or placeholder */
export function artworkUrl(path) {
  if (!path) return null;
  if (path.startsWith("http")) return path;
  return `/artwork/${path}`;
}

/** Get game bundle URL */
export function bundleUrl(game) {
  if (!game) return null;
  if (game.bundle_type === "sockdrive") {
    return `/api/sockdrive/${game.id}/file?path=.jsdos/dosbox.conf`;
  }
  return `/games/${game.id}.jsdos`;
}
