<?php

namespace App\Modules\Integrations\Platform\Services;

use Illuminate\Support\Facades\Crypt;

final class WebhookSigner
{
    /**
     * @param  array<string, mixed>  $payload
     * @return array{signature:string,timestamp:int}
     */
    public function sign(string $secretEnc, string $eventId, array $payload, ?int $timestamp = null): array
    {
        $timestamp = $timestamp ?? time();
        $secret = Crypt::decryptString($secretEnc);
        $body = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $base = $timestamp.'.'.$eventId.'.'.$body;
        $sig = hash_hmac('sha256', $base, $secret);

        return ['signature' => 'v1='.$sig, 'timestamp' => $timestamp];
    }
}

