using MongoDB.Bson;

namespace StellaOps.Feedser.Source.Ru.Bdu.Internal;

internal sealed record RuBduCursor(
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings,
    DateTimeOffset? LastSuccessfulFetch)
{
    private static readonly IReadOnlyCollection<Guid> EmptyGuids = Array.Empty<Guid>();

    public static RuBduCursor Empty { get; } = new(EmptyGuids, EmptyGuids, null);

    public RuBduCursor WithPendingDocuments(IEnumerable<Guid> documents)
        => this with { PendingDocuments = (documents ?? Enumerable.Empty<Guid>()).Distinct().ToArray() };

    public RuBduCursor WithPendingMappings(IEnumerable<Guid> mappings)
        => this with { PendingMappings = (mappings ?? Enumerable.Empty<Guid>()).Distinct().ToArray() };

    public RuBduCursor WithLastSuccessfulFetch(DateTimeOffset? timestamp)
        => this with { LastSuccessfulFetch = timestamp };

    public BsonDocument ToBsonDocument()
    {
        var document = new BsonDocument
        {
            ["pendingDocuments"] = new BsonArray(PendingDocuments.Select(id => id.ToString())),
            ["pendingMappings"] = new BsonArray(PendingMappings.Select(id => id.ToString())),
        };

        if (LastSuccessfulFetch.HasValue)
        {
            document["lastSuccessfulFetch"] = LastSuccessfulFetch.Value.UtcDateTime;
        }

        return document;
    }

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

        var pendingDocuments = ReadGuidArray(document, "pendingDocuments");
        var pendingMappings = ReadGuidArray(document, "pendingMappings");
        var lastFetch = document.TryGetValue("lastSuccessfulFetch", out var fetchValue)
            ? ParseDate(fetchValue)
            : null;

        return new RuBduCursor(pendingDocuments, pendingMappings, lastFetch);
    }

    private static IReadOnlyCollection<Guid> ReadGuidArray(BsonDocument document, string field)
    {
        if (!document.TryGetValue(field, out var value) || value is not BsonArray array)
        {
            return EmptyGuids;
        }

        var result = new List<Guid>(array.Count);
        foreach (var element in array)
        {
            if (Guid.TryParse(element?.ToString(), out var guid))
            {
                result.Add(guid);
            }
        }

        return result;
    }

    private static DateTimeOffset? ParseDate(BsonValue value)
        => value.BsonType switch
        {
            BsonType.DateTime => DateTime.SpecifyKind(value.ToUniversalTime(), DateTimeKind.Utc),
            BsonType.String when DateTimeOffset.TryParse(value.AsString, out var parsed) => parsed.ToUniversalTime(),
            _ => null,
        };
}
