<?php

namespace Modules\Shared\Bnfexpress\Support;

/**
 * bnfexpress's backend-to-backend admin auth scheme: every request carries
 * X-Client-Id/X-Timestamp/X-Signature, where the signature is a hex HMAC-SHA256
 * over "{METHOD}\n{PATH}\n{TIMESTAMP}\n{RAW_BODY}" (uppercase verb, path only —
 * no scheme/host/query — and the exact raw JSON bytes being sent, or "" for a
 * bodyless request). Timestamps are generated fresh per call — bnfexpress
 * rejects anything more than 300s from server time — so headers() must never
 * be memoized/reused across requests.
 */
class BnfexpressSignature
{
    /**
     * @param  int|null  $timestamp  Overrides the current time; only ever passed in tests.
     * @return array{'X-Client-Id': string, 'X-Timestamp': string, 'X-Signature': string}
     */
    public static function headers(string $method, string $path, string $rawBody, string $clientId, string $secret, ?int $timestamp = null): array
    {
        $timestamp = (string) ($timestamp ?? time());

        $payload = strtoupper($method)."\n".$path."\n".$timestamp."\n".$rawBody;

        return [
            'X-Client-Id' => $clientId,
            'X-Timestamp' => $timestamp,
            'X-Signature' => hash_hmac('sha256', $payload, $secret),
        ];
    }
}
