using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace StellaOps.Authority.Revocation;

internal sealed class AuthorityRevocationExportService
{
    private readonly RevocationBundleBuilder bundleBuilder;
    private readonly RevocationBundleSigner signer;
    private readonly ILogger<AuthorityRevocationExportService> logger;

    public AuthorityRevocationExportService(
        RevocationBundleBuilder bundleBuilder,
        RevocationBundleSigner signer,
        ILogger<AuthorityRevocationExportService> logger)
    {
        this.bundleBuilder = bundleBuilder ?? throw new ArgumentNullException(nameof(bundleBuilder));
        this.signer = signer ?? throw new ArgumentNullException(nameof(signer));
        this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<RevocationExportPackage> ExportAsync(CancellationToken cancellationToken)
    {
        var buildResult = await bundleBuilder.BuildAsync(cancellationToken).ConfigureAwait(false);
        var signature = await signer.SignAsync(buildResult.CanonicalJson, cancellationToken).ConfigureAwait(false);

        logger.LogInformation(
            "Generated revocation bundle sequence {Sequence} with {EntryCount} entries (sha256:{Hash}).",
            buildResult.Sequence,
            buildResult.Bundle.Revocations.Count,
            buildResult.Sha256);

        return new RevocationExportPackage(buildResult, signature);
    }
}
