<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Auth;

/**
 * Inbound payment-webhook HMAC verifier.
 *
 * Verifies the `x-simplyin-webhook-signature` header against the raw request body and the
 * Unix-seconds `x-simplyin-webhook-timestamp` header, using the per-shop secret registered with
 * the backend.
 *
 * This signature format must stay byte-for-byte identical to what the backend and the other
 * Simply.IN plugins compute — do not change it without coordinating across all receivers.
 *
 * Pure and side-effect free so it can be unit-tested.
 */
class WebhookSignatureVerifier
{
    /** Replay window in seconds (±) around the signed timestamp. */
    private const FRESHNESS_WINDOW_SECONDS = 900;

    /**
     * Verify a webhook signature.
     *
     * @param string $rawBody Exact request body bytes.
     * @param string $timestamp Value of the x-simplyin-webhook-timestamp header.
     * @param string $signature Value of the x-simplyin-webhook-signature header (hex).
     * @param string $secret Decrypted per-shop signing secret.
     * @return bool
     */
    public function verify(string $rawBody, string $timestamp, string $signature, string $secret): bool
    {
        if ($secret === '' || $signature === '' || $timestamp === '') {
            return false;
        }

        // Signature must be a 64-char SHA-256 hex digest. Normalize case before comparison:
        // hash_equals() is case-sensitive while hash_hmac() emits lowercase.
        if (strlen($signature) !== 64 || !ctype_xdigit($signature)) {
            return false;
        }
        $signature = strtolower($signature);

        // Timestamp must be a plain integer string — the exact bytes the HMAC was computed over.
        if (!ctype_digit($timestamp) || strlen($timestamp) > 20) {
            return false;
        }
        if (abs(time() - (int)$timestamp) > self::FRESHNESS_WINDOW_SECONDS) {
            return false;
        }

        $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);

        return hash_equals($expected, $signature);
    }
}
