<?php

declare(strict_types=1);

namespace App\Services\Alerts;

use App\Models\AlertDestination;
use App\Models\AlertRule;

class AlertFingerprintService
{
    /**
     * @param  array<string, mixed>  $event
     */
    public function hash(AlertRule $rule, AlertDestination $destination, int $tenantId, array $event): string
    {
        $fingerprintKey = trim((string) ($event['fingerprint_key'] ?? ''));

        if ($fingerprintKey === '') {
            $fingerprintKey = trim((string) ($event['idempotency_key'] ?? ''));
        }

        $payload = [
            'workspace_id' => (int) $rule->workspace_id,
            'rule_id' => (int) $rule->getKey(),
            'destination_id' => (int) $destination->getKey(),
            'managed_environment_id' => $tenantId,
            'event_type' => trim((string) ($event['event_type'] ?? '')),
            'severity' => strtolower(trim((string) ($event['severity'] ?? ''))),
            'fingerprint_key' => $fingerprintKey,
        ];

        return hash('sha256', json_encode($this->normalizeArray($payload), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
    }

    /**
     * @param  array<string, mixed>  $payload
     * @return array<string, mixed>
     */
    private function normalizeArray(array $payload): array
    {
        ksort($payload);

        foreach ($payload as $key => $value) {
            if (is_array($value)) {
                $payload[$key] = $this->normalizeArray($value);
            }
        }

        return $payload;
    }
}
