/**
 * Checkout Builder API helpers.
 *
 * Provides functions to interact with the Checkout Builder REST endpoints.
 *
 * @package ArraySubsPro
 */
import { buildUrl } from "@libs/url";

const getApiConfig = () => {
  const { env } = window.arraySubs || {};
  return {
    apiBase: env?.apiBaseUrl || "",
    nonce: env?.nonce || "",
  };
};

const request = async (path, options = {}) => {
  const { apiBase, nonce } = getApiConfig();
  const url = buildUrl(`${apiBase}arraysubs/v1/checkout-builder${path}`);
  const response = await fetch(url, {
    headers: {
      "Content-Type": "application/json",
      "X-WP-Nonce": nonce,
      ...options.headers,
    },
    ...options,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({}));
    throw new Error(error.message || "Request failed");
  }

  return response.json();
};

export const fetchConfig = () => request("/config");

export const saveConfig = (config) =>
  request("/config", {
    method: "POST",
    body: JSON.stringify({ config }),
  });

export const fetchDefaults = () => request("/defaults");

export const fetchFieldTypes = () => request("/field-types");
