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

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

internal sealed record ChromiumCursor(
    DateTimeOffset? LastPublished,
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings,
    IReadOnlyDictionary<string, ChromiumFetchCacheEntry> FetchCache)
{
    public static ChromiumCursor Empty { get; } = new(null, Array.Empty<Guid>(), Array.Empty<Guid>(), new Dictionary<string, ChromiumFetchCacheEntry>(StringComparer.Ordinal));

    public BsonDocument ToBsonDocument()
    {
        var document = new BsonDocument();
        if (LastPublished.HasValue)
        {
            document["lastPublished"] = LastPublished.Value.UtcDateTime;
        }

        document["pendingDocuments"] = new BsonArray(PendingDocuments.Select(id => id.ToString()));
        document["pendingMappings"] = new BsonArray(PendingMappings.Select(id => id.ToString()));

        if (FetchCache.Count > 0)
        {
            var cacheDocument = new BsonDocument();
            foreach (var (key, entry) in FetchCache)
            {
                cacheDocument[key] = entry.ToBson();
            }

            document["fetchCache"] = cacheDocument;
        }

        return document;
    }

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

        DateTimeOffset? lastPublished = null;
        if (document.TryGetValue("lastPublished", out var lastPublishedValue))
        {
            lastPublished = ReadDateTime(lastPublishedValue);
        }

        var pendingDocuments = ReadGuidArray(document, "pendingDocuments");
        var pendingMappings = ReadGuidArray(document, "pendingMappings");
        var fetchCache = ReadFetchCache(document);

        return new ChromiumCursor(lastPublished, pendingDocuments, pendingMappings, fetchCache);
    }

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

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

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

    public ChromiumCursor WithFetchCache(IDictionary<string, ChromiumFetchCacheEntry> cache)
        => this with { FetchCache = cache is null ? new Dictionary<string, ChromiumFetchCacheEntry>(StringComparer.Ordinal) : new Dictionary<string, ChromiumFetchCacheEntry>(cache, StringComparer.Ordinal) };

    public bool TryGetFetchCache(string key, out ChromiumFetchCacheEntry entry)
        => FetchCache.TryGetValue(key, out entry);

    private static DateTimeOffset? ReadDateTime(BsonValue value)
    {
        return 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 list = new List<Guid>(array.Count);
        foreach (var element in array)
        {
            if (Guid.TryParse(element.ToString(), out var guid))
            {
                list.Add(guid);
            }
        }

        return list;
    }

    private static IReadOnlyDictionary<string, ChromiumFetchCacheEntry> ReadFetchCache(BsonDocument document)
    {
        if (!document.TryGetValue("fetchCache", out var value) || value is not BsonDocument cacheDocument)
        {
            return new Dictionary<string, ChromiumFetchCacheEntry>(StringComparer.Ordinal);
        }

        var dictionary = new Dictionary<string, ChromiumFetchCacheEntry>(StringComparer.Ordinal);
        foreach (var element in cacheDocument.Elements)
        {
            if (element.Value is BsonDocument entryDocument)
            {
                dictionary[element.Name] = ChromiumFetchCacheEntry.FromBson(entryDocument);
            }
        }

        return dictionary;
    }
}

internal sealed record ChromiumFetchCacheEntry(string Sha256)
{
    public static ChromiumFetchCacheEntry Empty { get; } = new(string.Empty);

    public BsonDocument ToBson()
    {
        var document = new BsonDocument
        {
            ["sha256"] = Sha256,
        };

        return document;
    }

    public static ChromiumFetchCacheEntry FromBson(BsonDocument document)
    {
        var sha = document.TryGetValue("sha256", out var shaValue) ? shaValue.AsString : string.Empty;
        return new ChromiumFetchCacheEntry(sha);
    }
}
