export function buildRestUrl(path) {
  const base = window?.BookaroData?.rest_url || '/wp-json/';
  if (!path) {
    return base;
  }
  const baseNormalized = base.endsWith('/') ? base : `${base}/`;
  let nextPath = path;

  if (typeof path === 'string' && (path.startsWith('http://') || path.startsWith('https://'))) {
    try {
      const url = new URL(path);
      const baseOrigin = new URL(baseNormalized, window.location.origin).origin;
      if (url.origin !== baseOrigin) {
        return baseNormalized;
      }
      nextPath = `${url.pathname}${url.search}${url.hash}`;
    } catch (e) {
      return baseNormalized;
    }
  }

  const baseUrl = new URL(baseNormalized, window.location.origin);
  const basePath = baseUrl.pathname.replace(/\/+$/, '');
  if (
    nextPath === basePath ||
    nextPath.startsWith(`${basePath}/`) ||
    nextPath.startsWith(`${basePath}?`) ||
    nextPath.startsWith(`${basePath}#`)
  ) {
    nextPath = nextPath.slice(basePath.length);
  }

  let rel = nextPath.replace(/^\/+/, '');
  // Plain-permalink rest_url is ".../index.php?rest_route=/" — it already contains
  // a "?", so a query "?" inside the path must become "&". Otherwise WordPress folds
  // "endpoint?foo=bar" into the literal route name and the request 404s.
  if ( baseNormalized.indexOf('?') !== -1 ) {
    rel = rel.replace('?', '&');
  }
  return `${baseNormalized}${rel}`;
}

export async function restRequest(path, options = {}) {
  const { method = 'GET', data = null, headers = {} } = options;
  const nonce = window?.BookaroData?.rest_nonce || '';

  const request = {
    method,
    headers: {
      ...(nonce ? { 'X-WP-Nonce': nonce } : {}),
      ...headers
    }
  };

  if (data && method !== 'GET') {
    request.headers['Content-Type'] = 'application/json';
    request.body = JSON.stringify(data);
  }

  const response = await fetch(buildRestUrl(path), request);
  let payload = null;
  try {
    payload = await response.json();
  } catch (e) {
    payload = null;
  }

  if (!response.ok) {
    const fallbackMessage = window?.BookaroData?.i18n?.request_failed || window?.BookaroData?.i18n?.generic_error || '';
    const message = payload?.message || payload?.data?.message || fallbackMessage || payload?.code || '';
    const error = new Error(message);
    error.payload = payload;
    error.status = response.status;
    throw error;
  }

  return payload;
}
