<?php

declare(strict_types=1);

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

    /**
     * @param array<string, mixed> $payload
     * @return array<string, mixed>|null
     */
    public function emitTestEvent(string $flowId, string $eventName, array $payload, bool $consented): ?array
    {
        if (!$consented) {
            return $this->flows->recordAudit($flowId, null, 'capi.' . myronNormalizeSlug($eventName), 'skipped-no-consent', [
                'eventName' => trim($eventName),
                'deliveryMode' => 'test-audit-only',
            ]);
        }

        return $this->flows->recordAudit($flowId, null, 'capi.' . myronNormalizeSlug($eventName), 'recorded-test', [
            'eventName' => trim($eventName),
            'payload' => $this->sanitizePayload($payload),
            '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, 'access')) {
                $sanitized[(string) $key] = myronMaskSecret(is_scalar($value) ? (string) $value : json_encode($value, JSON_THROW_ON_ERROR));
                continue;
            }

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

        return $sanitized;
    }
}
