using System;
using MongoDB.Bson;

namespace StellaOps.Feedser.Source.Distro.Debian.Internal;

internal sealed record DebianFetchCacheEntry(string? ETag, DateTimeOffset? LastModified)
{
    public static DebianFetchCacheEntry Empty { get; } = new(null, null);

    public static DebianFetchCacheEntry FromDocument(StellaOps.Feedser.Storage.Mongo.Documents.DocumentRecord document)
        => new(document.Etag, document.LastModified);

    public static DebianFetchCacheEntry FromBson(BsonDocument document)
    {
        if (document is null || document.ElementCount == 0)
        {
            return Empty;
        }

        string? etag = null;
        DateTimeOffset? lastModified = null;

        if (document.TryGetValue("etag", out var etagValue) && etagValue.BsonType == BsonType.String)
        {
            etag = etagValue.AsString;
        }

        if (document.TryGetValue("lastModified", out var modifiedValue))
        {
            lastModified = modifiedValue.BsonType switch
            {
                BsonType.String when DateTimeOffset.TryParse(modifiedValue.AsString, out var parsed) => parsed.ToUniversalTime(),
                BsonType.DateTime => DateTime.SpecifyKind(modifiedValue.ToUniversalTime(), DateTimeKind.Utc),
                _ => null,
            };
        }

        return new DebianFetchCacheEntry(etag, lastModified);
    }

    public BsonDocument ToBsonDocument()
    {
        var document = new BsonDocument();
        if (!string.IsNullOrWhiteSpace(ETag))
        {
            document["etag"] = ETag;
        }

        if (LastModified.HasValue)
        {
            document["lastModified"] = LastModified.Value.UtcDateTime;
        }

        return document;
    }

    public bool Matches(StellaOps.Feedser.Storage.Mongo.Documents.DocumentRecord document)
    {
        if (document is null)
        {
            return false;
        }

        if (!string.Equals(document.Etag, ETag, StringComparison.Ordinal))
        {
            return false;
        }

        if (LastModified.HasValue && document.LastModified.HasValue)
        {
            return LastModified.Value.UtcDateTime == document.LastModified.Value.UtcDateTime;
        }

        return !LastModified.HasValue && !document.LastModified.HasValue;
    }
}
