<?php

declare( strict_types=1 );

namespace Brightfern\Support\Http;

/**
 * WordPress-backed HTTP client using the HTTP API (wp_remote_*). This is the
 * only place in the validators that touches WordPress, which keeps the rules
 * themselves portable and testable.
 */
final class WpHttpClient implements HttpClient {

	public function get( string $url, array $headers = array(), int $timeout = 10 ): HttpResponse {
		return $this->toResponse(
			\wp_remote_get( $url, array( 'headers' => $headers, 'timeout' => $timeout ) )
		);
	}

	public function post( string $url, string $body, array $headers = array(), int $timeout = 15 ): HttpResponse {
		return $this->toResponse(
			\wp_remote_post( $url, array( 'headers' => $headers, 'body' => $body, 'timeout' => $timeout ) )
		);
	}

	/**
	 * @param array|\WP_Error $response
	 */
	private function toResponse( $response ): HttpResponse {
		if ( \is_wp_error( $response ) ) {
			// Transport-level failure → status 0 so callers treat it as "unreachable".
			return new HttpResponse( 0, '', $response->get_error_message() );
		}

		return new HttpResponse(
			(int) \wp_remote_retrieve_response_code( $response ),
			(string) \wp_remote_retrieve_body( $response )
		);
	}
}
