using System.Text;
using System.Text.Json;

namespace Flo.Installer;

internal sealed class ManifestClient(HttpClient http)
{
    public async Task<Manifest> DownloadAndVerifyAsync(
        Uri manifestUrl,
        ReadOnlyMemory<byte> trustedPublicKey,
        CancellationToken ct)
    {
        var sigUrl = new Uri(manifestUrl + ".sig");

        byte[] manifestBytes = await http.GetByteArrayAsync(manifestUrl, ct);
        byte[] sigText = await http.GetByteArrayAsync(sigUrl, ct);
        byte[] signature = Convert.FromBase64String(Encoding.UTF8.GetString(sigText).Trim());

        if (!Ed25519Verifier.Verify(trustedPublicKey.Span, manifestBytes, signature))
            throw new InvalidOperationException("Manifest signature verification failed.");

        return JsonSerializer.Deserialize<Manifest>(manifestBytes)
            ?? throw new InvalidOperationException("Manifest deserialized to null.");
    }
}
