<?php

namespace WPD_Platform\Services;

use WPD_Platform\Plugin;
use WPD_Platform\Singleton;
use WPD_Platform\Utils\HostInterface;

/**
 * ChqApiClient class
 *
 * Reusable HTTP client for communication with CHQ (Control HQ) server.
 * Handles authentication via HMAC signatures and provides a consistent
 * interface for all outgoing requests to CHQ.
 *
 * @package WPD_Platform\Services
 */
class ChqApiClient extends Singleton
{
    /**
     * Default request timeout in seconds
     *
     * @var int
     */
    protected const DEFAULT_TIMEOUT = 60;

    /**
     * Send a POST request to CHQ
     *
     * @param string $endpoint The endpoint path (e.g., 'trigger-update', 'trigger-fired')
     * @param array  $payload  The data to send
     * @param array  $options  Additional options (timeout, etc.)
     *
     * @return array|\WP_Error Response array or WP_Error on failure
     */
    public function post(string $endpoint, array $payload = [], array $options = [])
    {
        $payload = $this->prepare_payload($payload);
        $signature = $this->generate_signature($payload);
        $timeout = $options['timeout'] ?? self::DEFAULT_TIMEOUT;

        $response = wp_remote_request(
            $this->get_base_url() . $endpoint,
            [
                'method'  => 'POST',
                'headers' => [
                    'Signature'    => $signature,
                    'Content-Type' => 'application/json',
                ],
                'body'    => wp_json_encode($payload),
                'timeout' => $timeout,
            ]
        );

        return $response;
    }

    /**
     * Prepare the payload by adding required fields
     *
     * @param array $payload The original payload
     *
     * @return array The prepared payload with hash included
     */
    protected function prepare_payload(array $payload): array
    {
        // Always include the site hash for identification
        if (!isset($payload['hash'])) {
            $payload['hash'] = Plugin::instance()->get_host()->get_token();
        }

        return $payload;
    }

    /**
     * Generate HMAC-SHA256 signature for the payload
     *
     * @param array $payload The payload to sign
     *
     * @return string The HMAC signature
     */
    protected function generate_signature(array $payload): string
    {
        return hash_hmac('sha256', json_encode($payload), HostInterface::API_SIGNATURE);
    }

    /**
     * Get the CHQ base URL
     *
     * @return string
     */
    protected function get_base_url(): string
    {
        // Allow override via constant for development/testing
        if (defined('WPD_CHQ_BASE_URL')) {
            return trailingslashit(WPD_CHQ_BASE_URL);
        }

        return HostInterface::API_BASE_URL;
    }

    /**
     * Check if the last request was successful
     *
     * @param array|\WP_Error $response The response from a request
     *
     * @return bool
     */
    public function is_success($response): bool
    {
        if (is_wp_error($response)) {
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        return $code >= 200 && $code < 300;
    }

    /**
     * Get the response body as an array
     *
     * @param array|\WP_Error $response The response from a request
     *
     * @return array|null
     */
    public function get_body($response): ?array
    {
        if (is_wp_error($response)) {
            return null;
        }

        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }
}
