const API_BASE = import.meta.env.VITE_API_BASE || "";

async function parseResponse(response) {
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload.detail || "Request failed");
  }
  return payload;
}

export async function uploadImage(file) {
  const body = new FormData();
  body.append("image", file);
  const response = await fetch(`${API_BASE}/api/images/`, {
    method: "POST",
    body
  });
  return parseResponse(response);
}

export async function getOperations() {
  const response = await fetch(`${API_BASE}/api/operations/`);
  return parseResponse(response);
}

export async function listStates(sessionId) {
  const response = await fetch(`${API_BASE}/api/sessions/${sessionId}/states/`);
  return parseResponse(response);
}

export async function applyStateOperation(stateId, operation, params = {}) {
  const response = await fetch(`${API_BASE}/api/states/${stateId}/operations/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ operation, params })
  });
  return parseResponse(response);
}

export async function combineStates(operation, stateIds, params = {}) {
  const response = await fetch(`${API_BASE}/api/states/combine/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ operation, state_ids: stateIds, params })
  });
  return parseResponse(response);
}

export async function getStateHistogram(stateId) {
  const response = await fetch(`${API_BASE}/api/states/${stateId}/histogram/`);
  return parseResponse(response);
}

export async function deleteState(stateId) {
  const response = await fetch(`${API_BASE}/api/states/${stateId}/`, {
    method: "DELETE"
  });
  if (response.status === 204) return {};
  return parseResponse(response);
}

export async function processImage(sessionId, operation, params) {
  const response = await fetch(`${API_BASE}/api/process/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ session_id: sessionId, operation, params })
  });
  return parseResponse(response);
}

export async function createBatch(operation, sessionIds, params = {}) {
  const response = await fetch(`${API_BASE}/api/batch/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ operation, session_ids: sessionIds, params })
  });
  return parseResponse(response);
}

export async function getJob(jobId) {
  const response = await fetch(`${API_BASE}/api/jobs/${jobId}/`);
  return parseResponse(response);
}
