using MongoDB.Bson;

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

internal sealed record RuNkckiCursor(
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings,
    IReadOnlyCollection<string> KnownBulletins,
    DateTimeOffset? LastListingFetchAt)
{
    private static readonly IReadOnlyCollection<Guid> EmptyGuids = Array.Empty<Guid>();
    private static readonly IReadOnlyCollection<string> EmptyBulletins = Array.Empty<string>();

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

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

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

    public RuNkckiCursor WithKnownBulletins(IEnumerable<string> bulletins)
        => this with { KnownBulletins = (bulletins ?? Enumerable.Empty<string>()).Where(static id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray() };

    public RuNkckiCursor WithLastListingFetch(DateTimeOffset? timestamp)
        => this with { LastListingFetchAt = timestamp };

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

        if (LastListingFetchAt.HasValue)
        {
            document["lastListingFetchAt"] = LastListingFetchAt.Value.UtcDateTime;
        }

        return document;
    }

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

        var pendingDocuments = ReadGuidArray(document, "pendingDocuments");
        var pendingMappings = ReadGuidArray(document, "pendingMappings");
        var knownBulletins = ReadStringArray(document, "knownBulletins");
        var lastListingFetch = document.TryGetValue("lastListingFetchAt", out var dateValue)
            ? ParseDate(dateValue)
            : null;

        return new RuNkckiCursor(pendingDocuments, pendingMappings, knownBulletins, lastListingFetch);
    }

    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 IReadOnlyCollection<string> ReadStringArray(BsonDocument document, string field)
    {
        if (!document.TryGetValue(field, out var value) || value is not BsonArray array)
        {
            return EmptyBulletins;
        }

        var result = new List<string>(array.Count);
        foreach (var element in array)
        {
            var text = element?.ToString();
            if (!string.IsNullOrWhiteSpace(text))
            {
                result.Add(text);
            }
        }

        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,
        };
}
