<?php

/**
 * Log requests to the WordPress.org Events API and their responses.
 *
 * @param array|WP_Error $response     HTTP response or WP_Error object.
 * @param string         $context      Context under which the hook is fired.
 * @param string         $transport    HTTP transport used.
 * @param array          $request_args HTTP request arguments.
 * @param string         $request_url  The request URL.
 */
function debug_community_events_response( $response, $context, $transport, $request_args, $request_url ) {
	if ( false === strpos( $request_url, 'api.wordpress.org/events' ) ) {
		return;
	}

	$response_code  = wp_remote_retrieve_response_code( $response );
	$response_body  = json_decode( wp_remote_retrieve_body( $response ), true );
	$response_error = null;

	// Avoid bloating the log with all the event data, but keep the count.
	if ( isset( $response_body['events'] ) ) {
		$response_body['events'] = count( $response_body['events'] ) . ' events trimmed.';
	}

	$message      = is_wp_error( $response ) ? $response->get_error_message() : 'Valid response received';
	$request_args = $request_args['body'];
	$details      = compact( 'request_url', 'request_args', 'response_code', 'response_body' );

	error_log( sprintf(
		'%s: %s. Details: %s',
		__METHOD__,
		trim( $message, '.' ),
		wp_json_encode( $details )
	) );
}
add_action( 'http_api_debug', 'debug_community_events_response', 10, 5 );
