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

namespace StellaOps.Feedser.Source.Vndr.Msrc.Internal;

internal sealed record MsrcCursor(
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings,
    DateTimeOffset? LastModifiedCursor)
{
    private static readonly IReadOnlyCollection<Guid> EmptyGuidSet = Array.Empty<Guid>();

    public static MsrcCursor Empty { get; } = new(EmptyGuidSet, EmptyGuidSet, null);

    public MsrcCursor WithPendingDocuments(IEnumerable<Guid> documents)
        => this with { PendingDocuments = Distinct(documents) };

    public MsrcCursor WithPendingMappings(IEnumerable<Guid> mappings)
        => this with { PendingMappings = Distinct(mappings) };

    public MsrcCursor WithLastModifiedCursor(DateTimeOffset? timestamp)
        => this with { LastModifiedCursor = 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 (LastModifiedCursor.HasValue)
        {
            document["lastModifiedCursor"] = LastModifiedCursor.Value.UtcDateTime;
        }

        return document;
    }

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

        var pendingDocuments = ReadGuidArray(document, "pendingDocuments");
        var pendingMappings = ReadGuidArray(document, "pendingMappings");
        var lastModified = document.TryGetValue("lastModifiedCursor", out var value)
            ? ParseDate(value)
            : null;

        return new MsrcCursor(pendingDocuments, pendingMappings, lastModified);
    }

    private static IReadOnlyCollection<Guid> Distinct(IEnumerable<Guid>? values)
        => values?.Distinct().ToArray() ?? EmptyGuidSet;

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

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

        return items;
    }

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