<?php

namespace PloverCRM\Modules\ContactEnrichment\Services;

use PloverCRM\Common\LicenseChecker;

/**
 * Relays post-create job scheduling through the hub.
 */
class PostCreateJobRelay
{
    private const API_NAMESPACE = '/wp-json/plovercrm-hub/v1';

    public static function enqueue(string $jobId, string $dispatchToken)
    {
        $license = LicenseChecker::getLicense();
        $token = sanitize_text_field((string) ($license['token'] ?? ''));

        if ($token === '') {
            return new \WP_Error(
                'license_inactive',
                'A valid hub activation is required before background lead jobs can run.'
            );
        }

        $body = wp_json_encode([
            'job_id' => sanitize_text_field($jobId),
            'dispatch_token' => sanitize_text_field($dispatchToken),
        ]);

        if ($body === false) {
            return new \WP_Error('json_encode_failed', 'Failed to encode the post-create job payload.');
        }

        $hubUrl = untrailingslashit(LicenseChecker::getHubUrl()) . self::API_NAMESPACE . '/background-jobs/contact-post-create/enqueue';

        $response = wp_remote_post($hubUrl, [
            'timeout' => 15,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
                'X-PloverCRM-Token' => $token,
                'X-PloverCRM-Service' => 'contact-post-create-job',
            ],
            'body' => $body,
            'data_format' => 'body',
        ]);

        if (is_wp_error($response)) {
            return $response;
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $decoded = json_decode((string) wp_remote_retrieve_body($response), true);
        $message = sanitize_text_field((string) ($decoded['message'] ?? $decoded['error'] ?? ''));

        if ($status < 200 || $status >= 300) {
            return new \WP_Error(
                'background_job_enqueue_failed',
                $message !== '' ? $message : 'Failed to enqueue the background lead job.',
                [
                    'status' => 503,
                    'hub_status' => $status,
                    'response' => $decoded,
                ]
            );
        }

        return is_array($decoded) ? $decoded : [
            'success' => true,
            'data' => [],
        ];
    }
}
