<?php
/**
 * Variant Telemetry HTTP Client.
 *
 * @package AIPT\Core\Telemetry
 * @since   2.6.2
 */

declare(strict_types=1);

namespace AIPT\Core\Telemetry;

defined('ABSPATH') || exit;

/**
 * Plain HTTP client for variant adoption telemetry.
 *
 * Anonymous POST — no authentication, no signing. Telemetry is best-effort
 * and the payload contains only non-sensitive fields (site URL + variant).
 * The 24h transient throttle in VariantTelemetryReporter is the only
 * spam-control layer on the plugin side; the backend has its own IP rate-limit.
 *
 * Decoupled from CreditApiClient because telemetry applies to ALL generator
 * tools, while the Ctrl credit ledger is exclusively for the Advanced
 * Description Generator + AutomationJobs pipeline (AGENTS.md "Ctrl Scope Rule").
 *
 * @since 2.6.2
 */
final class VariantTelemetryClient {

	private const API_BASE = 'https://api.aiforwoo.com/api/v2/';
	private const TIMEOUT  = 5;

	/**
	 * POST a payload to {API_BASE}{$endpoint}. Caller assembles the full body.
	 *
	 * @param string               $endpoint Relative path (e.g. 'variant-telemetry').
	 * @param array<string, mixed> $payload  Pre-assembled JSON body.
	 * @return array<string, mixed> Decoded response on 2xx, or {success: false, error: <code>} on failure.
	 */
	public function send(string $endpoint, array $payload): array {
		$url = self::API_BASE . ltrim($endpoint, '/');

		$body = wp_json_encode($payload);
		if ($body === false) {

			return ['success' => false, 'error' => 'encode_failed'];
		}

		$response = wp_remote_post($url, [
			'method'      => 'POST',
			'timeout'     => self::TIMEOUT,
			'redirection' => 0,
			'sslverify'   => true,
			'headers'     => [
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			],
			'body'        => $body,
		]);

		if (is_wp_error($response)) {
			return ['success' => false, 'error' => 'http_error'];
		}

		$status = (int) wp_remote_retrieve_response_code($response);
		if ($status < 200 || $status >= 300) {
			return ['success' => false, 'error' => 'http_' . $status];
		}

		$decoded = json_decode(wp_remote_retrieve_body($response), true);
		if (!is_array($decoded)) {
			return ['success' => false, 'error' => 'invalid_response'];
		}

		return $decoded;
	}
}
