using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;

namespace StellaOps.Feedser.Source.Ics.Cisa.Internal;

internal sealed record IcsCisaCursor(
    DateTimeOffset? LastPublished,
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings)
{
    public static IcsCisaCursor Empty { get; } = new(null, Array.Empty<Guid>(), Array.Empty<Guid>());

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

        if (LastPublished.HasValue)
        {
            document["lastPublished"] = LastPublished.Value.UtcDateTime;
        }

        return document;
    }

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

        var lastPublished = document.TryGetValue("lastPublished", out var publishedValue)
            ? ParseDate(publishedValue)
            : null;

        return new IcsCisaCursor(
            lastPublished,
            ReadGuidArray(document, "pendingDocuments"),
            ReadGuidArray(document, "pendingMappings"));
    }

    public IcsCisaCursor WithPendingDocuments(IEnumerable<Guid> ids)
        => this with { PendingDocuments = ids?.Distinct().ToArray() ?? Array.Empty<Guid>() };

    public IcsCisaCursor WithPendingMappings(IEnumerable<Guid> ids)
        => this with { PendingMappings = ids?.Distinct().ToArray() ?? Array.Empty<Guid>() };

    public IcsCisaCursor WithLastPublished(DateTimeOffset? published)
        => this with { LastPublished = published?.ToUniversalTime() };

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

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

        var results = new List<Guid>(array.Count);
        foreach (var element in array)
        {
            if (element is null)
            {
                continue;
            }

            if (Guid.TryParse(element.ToString(), out var guid))
            {
                results.Add(guid);
            }
        }

        return results;
    }
}
