<?php

declare(strict_types=1);

final class MyronWebhookDeliveryService
{
    public function __construct(
        private readonly MyronFunnelFlowRepository $flows,
    ) {
    }

    /**
     * @param array<string, mixed> $payload
     * @return array<string, mixed>
     */
    public function recordTestDelivery(string $flowId, string $eventType, string $destination, array $payload): array
    {
        $sanitizedPayload = $this->sanitizePayload($payload);

        return $this->flows->recordAudit($flowId, null, 'webhook.' . myronNormalizeSlug($eventType), 'queued-test', [
            'destination' => trim($destination),
            'payload' => $sanitizedPayload,
            'deliveryMode' => 'test-audit-only',
        ]);
    }

    /**
     * @param array<string, mixed> $payload
     * @return array<string, mixed>
     */
    private function sanitizePayload(array $payload): array
    {
        $sanitized = [];
        foreach ($payload as $key => $value) {
            $normalizedKey = strtolower((string) $key);
            if (str_contains($normalizedKey, 'secret') || str_contains($normalizedKey, 'token') || str_contains($normalizedKey, 'key')) {
                $sanitized[(string) $key] = myronMaskSecret(is_scalar($value) ? (string) $value : json_encode($value, JSON_THROW_ON_ERROR));
                continue;
            }

            $sanitized[(string) $key] = $value;
        }

        return $sanitized;
    }
}
