<?php

namespace WPSN\Modules\AI;

use WPSN\Core\Settings;
use WPSN\Modules\SaaSSync\SaaSSyncService;
use WPSN\Modules\Licensing\LicenseSecretsRepository;
use WPSN\Modules\Licensing\ServerContract;

defined('ABSPATH') || exit;

/**
 * Shared transport contract for SaaS AI requests.
 *
 * Goals:
 * - reuse the stable install identity / request signing layer from licensing,
 * - keep Authorization: Bearer for backward compatibility with older SaaS endpoints,
 * - allow AI routes to move onto the same server contract without breaking legacy payloads.
 */
final class SaaSAIRequestContract
{
    private Settings $settings;
    private SaaSSyncService $saas;
    private LicenseSecretsRepository $secrets;
    private ServerContract $serverContract;

    public function __construct(Settings $settings, SaaSSyncService $saas)
    {
        $this->settings = $settings;
        $this->saas = $saas;
        $this->secrets = new LicenseSecretsRepository();
        $this->serverContract = new ServerContract($settings, $this->secrets);
    }

    /**
     * @param array<string,mixed> $payload
     * @return array<string,mixed>
     */
    public function buildPayload(string $context, array $payload = []): array
    {
        $licenseKey = $this->licenseKey();
        if ($licenseKey !== '' && empty($payload['license_key'])) {
            $payload['license_key'] = $licenseKey;
        }

        return $this->serverContract->buildPayload($context, $payload, false);
    }

    /**
     * @param array<string,mixed> $payload
     * @return array<string,string>
     */
    public function buildHeaders(string $context, array $payload = []): array
    {
        $headers = $this->serverContract->buildHeaders('saas_ai_proxy', $context, $payload);
        $token = $this->authToken();
        if ($token !== '') {
            $headers['Authorization'] = 'Bearer ' . $token;
        }

        $headers['X-WPSN-Service'] = 'saas_ai_proxy';
        $headers['X-WPSN-Context'] = sanitize_key($context);

        return $headers;
    }

    /**
     * @param array<string,mixed> $payload
     */
    public function jsonEncode(array $payload): string
    {
        return $this->serverContract->jsonEncode($payload);
    }

    public function authToken(): string
    {
        return trim((string) $this->saas->getAuthToken());
    }

    public function licenseKey(): string
    {
        $licenseKey = trim((string) $this->secrets->getLicenseKey());
        if ($licenseKey !== '') {
            return $licenseKey;
        }

        return $this->authToken();
    }

    public function hasSignedBinding(): bool
    {
        return $this->serverContract->hasRequestSecret();
    }

    public function installId(): string
    {
        return $this->serverContract->installId();
    }

    public function siteFingerprint(): string
    {
        return $this->serverContract->siteFingerprint();
    }
}
