const defaultHeaders = { "Content-Type": "application/json" };

const metaBase = document.querySelector('meta[name="app-base"]')?.content || "";
const autoBase = (() => {
  const parts = window.location.pathname.split("/").filter(Boolean);
  return parts.length ? `/${parts[0]}` : "";
})();
const basePath = metaBase || autoBase;
const withBase = (path) => `${basePath}${path}`;

async function request(path, { method = "GET", body } = {}) {
  const res = await fetch(withBase(path), {
    method,
    credentials: "same-origin",
    headers: defaultHeaders,
    body: body ? JSON.stringify(body) : undefined,
  });

  if (!res.ok) {
    let msg = `${res.status}`;
    try {
      const data = await res.json();
      msg = data.error || JSON.stringify(data);
    } catch { /* ignore */ }
    const err = new Error(msg);
    err.status = res.status;
    throw err;
  }
  return res.status === 204 ? null : res.json();
}

export const api = {
  state: () => request("/api/state"),
  me: () => request("/api/me"),
  register: (payload) => request("/api/auth/register", { method: "POST", body: payload }),
  login: (payload) => request("/api/auth/login", { method: "POST", body: payload }),
  logout: () => request("/api/auth/logout", { method: "POST" }),

  mySuggestions: () => request("/api/suggestions/mine"),
  createSuggestion: (payload) => request("/api/suggestions", { method: "POST", body: payload }),
  deleteSuggestion: (id) => request(`/api/suggestions/${id}`, { method: "DELETE" }),
  updateSuggestion: (id, payload) => request(`/api/suggestions/${id}`, { method: "PUT", body: payload }),
  allSuggestions: () => request("/api/suggestions/all"),

  myVotes: () => request("/api/votes/mine"),
  vote: (suggestionId, score) => request("/api/votes", { method: "POST", body: { suggestionId, score } }),

  results: () => request("/api/results"),
};

export const adminApi = {
  setPhase: (phase) => request("/api/admin/phase", { method: "POST", body: { phase } }),
  reset: () => request("/api/admin/reset", { method: "POST" }),
  factoryReset: () => request("/api/admin/factory-reset", { method: "POST" }),
};
