/**
 * Utility for making authenticated internal API calls
 * Automatically forwards authentication cookies to prevent auth failures
 */

/**
 * Make an internal API call with forwarded authentication
 * @param event - The current event context
 * @param url - The API endpoint URL
 * @param options - Fetch options (method, body, etc.)
 */
export async function $internalFetch<T = any>(
  event: any,
  url: string,
  options: {
    method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
    body?: any;
    params?: Record<string, any>;
    headers?: Record<string, string>;
  } = {}
): Promise<T> {
  // Forward authentication cookies from the original request
  const cookies = getRequestHeader(event, "cookie");
  const requestHeaders: Record<string, string> = {
    ...options.headers,
  };
  
  if (cookies) {
    requestHeaders["cookie"] = cookies;
  }

  console.log(`[INTERNAL_API] Making authenticated internal call to: ${url}`);

  return await $fetch(url, {
    ...options,
    headers: requestHeaders,
  }) as T;
}

/**
 * Helper for internal API calls that require POST with JSON body
 */
export async function $internalPost<T = any>(
  event: any,
  url: string,
  body: any,
  additionalHeaders: Record<string, string> = {}
): Promise<T> {
  return $internalFetch<T>(event, url, {
    method: 'POST',
    body,
    headers: {
      'Content-Type': 'application/json',
      ...additionalHeaders,
    },
  });
}

/**
 * Helper for internal API calls that require GET with query params
 */
export async function $internalGet<T = any>(
  event: any,
  url: string,
  params: Record<string, any> = {}
): Promise<T> {
  return $internalFetch<T>(event, url, {
    method: 'GET',
    params,
  });
}
