<?php

declare(strict_types=1);

namespace EasyChat\Library\Update;

final class ReleaseManifestCanonicalizer
{
    public static function json(array $payload): string
    {
        $json = json_encode(
            self::normalize($payload),
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );
        if (!is_string($json)) {
            throw new \RuntimeException('update_manifest_canonicalization_failed');
        }

        return $json;
    }

    private static function normalize($value)
    {
        if (!is_array($value)) {
            return $value;
        }

        if ($value === [] || array_keys($value) === range(0, count($value) - 1)) {
            return array_map([self::class, 'normalize'], $value);
        }

        ksort($value, SORT_STRING);
        foreach ($value as $key => $item) {
            $value[$key] = self::normalize($item);
        }
        return $value;
    }
}
