/* global window */
class OpsApiError extends Error {
  constructor(status, code, message, details) {
    super(message);
    this.name = "OpsApiError";
    this.status = status;
    this.code = code;
    this.details = details;
  }
}

const OPS_API_BASE_URL = (window.OPS_CONFIG && window.OPS_CONFIG.apiBaseUrl) || "https://api.agronutikas.ee";

function buildOpsUrl(path) {
  const base = OPS_API_BASE_URL.replace(/\/+$/, "").replace(/\/api$/i, "");
  return `${base}${path.startsWith("/") ? path : `/${path}`}`;
}

function parseOpsJson(text) {
  if (!text) return { parsed: null, parseError: null };
  try {
    return { parsed: JSON.parse(text), parseError: null };
  } catch (error) {
    return {
      parsed: null,
      parseError: error instanceof Error ? error.message : String(error),
    };
  }
}

async function opsFetch(path, options = {}) {
  const response = await fetch(buildOpsUrl(path), {
    method: options.method || "GET",
    credentials: "include",
    headers: {
      accept: "application/json",
      ...(options.body ? { "content-type": "application/json" } : {}),
      ...(options.headers || {}),
    },
    body: options.body ? JSON.stringify(options.body) : undefined,
  });
  const text = await response.text();
  const { parsed, parseError } = parseOpsJson(text);
  if (parseError && response.ok) {
    throw new OpsApiError(response.status, "invalid_json", "Ops API returned malformed JSON", { rawText: text, parseError });
  }
  if (!response.ok) {
    const details = parseError ? { rawText: text, parseError } : parsed;
    throw new OpsApiError(response.status, `http_${response.status}`, parsed?.message || parsed?.error || response.statusText, details);
  }
  return parsed;
}

window.OpsApi = { OpsApiError, buildOpsUrl, opsFetch };
