/**
 * API Client utility for ProRank SEO
 *
 * Provides a fallback mechanism for API calls when apiFetch fails
 */

import apiFetch from '@wordpress/api-fetch';

/**
 * Make an API request with fallback support
 *
 * @param {Object} options        - Request options
 * @param {string} options.path   - API path
 * @param {string} options.method - HTTP method
 * @param {Object} options.data   - Request data
 * @return {Promise} API response
 */
export async function apiRequest(options) {
  const { path, method = 'GET', data } = options;

  try {
    // Try with apiFetch first
    return await apiFetch({
      path,
      method,
      data: method === 'GET' ? undefined : data,
    });
  } catch (apiFetchError) {
    // Fallback to direct fetch
    const url = window.prorankSeo.restUrl + path.replace(/^\//, '');
    const fetchOptions = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': window.prorankSeo.nonce,
      },
      credentials: 'same-origin',
    };

    if (method !== 'GET' && data) {
      fetchOptions.body = JSON.stringify(data);
    }

    const response = await fetch(url, fetchOptions);

    if (!response.ok) {
      const errorText = await response.text();

      // Try to parse JSON error response
      try {
        const errorData = JSON.parse(errorText);
        // If the error has a message field, use it
        if (errorData.message) {
          throw new Error(errorData.message);
        }
        throw new Error(JSON.stringify(errorData));
      } catch (parseError) {
        // If not valid JSON, throw the text as is
        throw new Error(errorText);
      }
    }

    return await response.json();
  }
}

/**
 * Make a GET request
 * @param path
 */
export function apiGet(path) {
  return apiRequest({ path, method: 'GET' });
}

/**
 * Make a POST request
 * @param path
 * @param data
 */
export function apiPost(path, data) {
  return apiRequest({ path, method: 'POST', data });
}

export default {
  request: apiRequest,
  get: apiGet,
  post: apiPost,
};
