/**
 * Enhanced Fetch Wrapper with Error Handling
 * Automatically redirects to error pages based on HTTP status codes
 * 
 * Note: adminApi.js uses its own adminFetch wrapper for CSRF token handling
 * and should not be migrated to this wrapper.
 */

const handleErrorResponse = (status) => {
  switch (status) {
    case 403:
      window.location.href = '/error/403';
      break;
    case 500:
      window.location.href = '/error/500';
      break;
    case 502:
      window.location.href = '/error/502';
      break;
    case 503:
      window.location.href = '/error/503';
      break;
    default:
      // Don't redirect for other errors (400, 401, etc.)
      break;
  }
};

/**
 * Enhanced fetch with automatic error page redirects
 * @param {string} url - The URL to fetch
 * @param {object} options - Fetch options
 * @returns {Promise<Response>} - The response object
 */
export const apiFetch = async (url, options = {}) => {
  try {
    const response = await fetch(url, {
      ...options,
      credentials: options.credentials || 'include'
    });

    // If response is not ok, handle error
    if (!response.ok) {
      handleErrorResponse(response.status);
    }

    return response;
  } catch (error) {
    // Network errors or other fetch failures
    console.error('Fetch error:', error);
    throw error;
  }
};

/**
 * Helper for GET requests
 */
export const apiGet = async (url) => {
  const response = await apiFetch(url, { method: 'GET' });
  return response.json();
};

/**
 * Helper for POST requests
 */
export const apiPost = async (url, body = null, options = {}) => {
  const fetchOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  };

  if (body) {
    fetchOptions.body = JSON.stringify(body);
  }

  const response = await apiFetch(url, fetchOptions);
  return response.json();
};

/**
 * Helper for PUT requests
 */
export const apiPut = async (url, body = null, options = {}) => {
  const fetchOptions = {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  };

  if (body) {
    fetchOptions.body = JSON.stringify(body);
  }

  const response = await apiFetch(url, fetchOptions);
  return response.json();
};

/**
 * Helper for DELETE requests
 */
export const apiDelete = async (url, options = {}) => {
  const response = await apiFetch(url, {
    method: 'DELETE',
    ...options
  });
  return response.json();
};

export default apiFetch;
