using System.Security.Cryptography;
using System.Text;
using Kbx.Shared.ExternalData.Generated;

namespace Kbx.Shared.ExternalData;

public static class KbxExternalDataProvenanceFactory
{
    public static string PayloadSha256(ReadOnlySpan<byte> payload) => Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
    public static string CacheKey(IEnumerable<KeyValuePair<string,string?>> values)
    {
        var canonical=string.Join("&",values.OrderBy(x=>x.Key,StringComparer.Ordinal).Select(x=>$"{x.Key}={x.Value?.Trim() ?? string.Empty}"));
        return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical))).ToLowerInvariant();
    }
    public static KbxExternalDataProvenance Create(KbxExternalDataDatasetDefinition d,KbxExternalDataState state,DateTimeOffset requestedAt,DateTimeOffset receivedAt,DateTimeOffset ingestedAt,DateTimeOffset? observedAt,DateTimeOffset? freshUntil,DateTimeOffset? usableUntil,string payloadSha,bool cacheHit,bool refreshInProgress=false,string? warning=null)
        => new(d.Id,d.ProviderId,d.ProviderOperationId,d.SourceLabel,state,observedAt,requestedAt,receivedAt,ingestedAt,freshUntil,usableUntil,payloadSha,d.NormalizerVersion,cacheHit,refreshInProgress,warning);
}
