<?php

namespace App\Services\Operations;

final class BulkIdempotencyFingerprint
{
    /**
     * @param  array<string, mixed>  $targetScope
     * @param  array{kind: string, ids_hash?: string, query_hash?: string}  $selectionIdentity
     */
    public function build(string $operationType, array $targetScope, array $selectionIdentity): string
    {
        $payload = [
            'type' => trim($operationType),
            'target_scope' => $targetScope,
            'selection' => $selectionIdentity,
        ];

        $payload = $this->ksortRecursive($payload);

        $json = json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        return hash('sha256', $json);
    }

    private function ksortRecursive(mixed $value): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        $isList = array_is_list($value);
        if (! $isList) {
            ksort($value);
        }

        foreach ($value as $key => $child) {
            $value[$key] = $this->ksortRecursive($child);
        }

        return $value;
    }
}
