<?php
/**
 * HTTP helpers for token and profile fetches.
 *
 * @package WP_PowerSuite\OAuth
 */

namespace WP_PowerSuite\OAuth;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class TokenHandler {

	/**
	 * @param array<string, string> $body
	 * @param array<string, string> $headers
	 */
	public function postForm( string $url, array $body, int $timeout = 15, array $headers = [] ): array|\WP_Error {
		$headers = array_merge( [ 'Content-Type' => 'application/x-www-form-urlencoded' ], $headers );
		$res     = wp_remote_post(
			$url,
			[
				'body'    => $body,
				'timeout' => $timeout,
				'headers' => $headers,
			]
		);
		if ( is_wp_error( $res ) ) {
			return $res;
		}
		$code = wp_remote_retrieve_response_code( $res );
		$raw  = wp_remote_retrieve_body( $res );
		$data = json_decode( $raw, true );
		if ( ! is_array( $data ) && $raw !== '' && json_last_error() !== JSON_ERROR_NONE ) {
			$data = [];
			parse_str( $raw, $data );
		}
		if ( $code < 200 || $code > 299 ) {
			$err = is_array( $data ) && isset( $data['error'] ) ? (string) $data['error'] : (string) $raw;
			return new \WP_Error( 'http_error', $err ?: __( 'Request failed.', 'wp-powersuite' ), [ 'status' => $code ] );
		}
		return is_array( $data ) ? $data : [];
	}

	/**
	 * @param array<string, string> $headers
	 */
	public function getJson( string $url, array $headers = [], int $timeout = 15 ): array|\WP_Error {
		$res = wp_remote_get( $url, [ 'headers' => $headers, 'timeout' => $timeout ] );
		if ( is_wp_error( $res ) ) {
			return $res;
		}
		$code = wp_remote_retrieve_response_code( $res );
		$raw  = wp_remote_retrieve_body( $res );
		$data = json_decode( $raw, true );
		if ( $code < 200 || $code > 299 ) {
			return new \WP_Error( 'http_error', (string) $raw, [ 'status' => $code ] );
		}
		if ( ! is_array( $data ) ) {
			return new \WP_Error(
				'http_error',
				$raw !== '' ? (string) $raw : __( 'Invalid response from provider.', 'wp-powersuite' ),
				[ 'status' => $code ]
			);
		}
		return $data;
	}
}
