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

namespace StellaOps.Feedser.Source.Distro.Suse.Internal;

internal sealed record SuseCursor(
    DateTimeOffset? LastModified,
    IReadOnlyCollection<string> ProcessedIds,
    IReadOnlyCollection<Guid> PendingDocuments,
    IReadOnlyCollection<Guid> PendingMappings,
    IReadOnlyDictionary<string, SuseFetchCacheEntry> FetchCache)
{
    private static readonly IReadOnlyCollection<string> EmptyStringList = Array.Empty<string>();
    private static readonly IReadOnlyCollection<Guid> EmptyGuidList = Array.Empty<Guid>();
    private static readonly IReadOnlyDictionary<string, SuseFetchCacheEntry> EmptyCache =
        new Dictionary<string, SuseFetchCacheEntry>(StringComparer.OrdinalIgnoreCase);

    public static SuseCursor Empty { get; } = new(null, EmptyStringList, EmptyGuidList, EmptyGuidList, EmptyCache);

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

        DateTimeOffset? lastModified = null;
        if (document.TryGetValue("lastModified", out var lastValue))
        {
            lastModified = lastValue.BsonType switch
            {
                BsonType.DateTime => DateTime.SpecifyKind(lastValue.ToUniversalTime(), DateTimeKind.Utc),
                BsonType.String when DateTimeOffset.TryParse(lastValue.AsString, out var parsed) => parsed.ToUniversalTime(),
                _ => null,
            };
        }

        var processed = ReadStringSet(document, "processedIds");
        var pendingDocs = ReadGuidSet(document, "pendingDocuments");
        var pendingMappings = ReadGuidSet(document, "pendingMappings");
        var cache = ReadCache(document);

        return new SuseCursor(lastModified, processed, pendingDocs, pendingMappings, cache);
    }

    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 (LastModified.HasValue)
        {
            document["lastModified"] = LastModified.Value.UtcDateTime;
        }

        if (ProcessedIds.Count > 0)
        {
            document["processedIds"] = new BsonArray(ProcessedIds);
        }

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

            document["fetchCache"] = cacheDocument;
        }

        return document;
    }

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

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

    public SuseCursor WithFetchCache(IDictionary<string, SuseFetchCacheEntry>? cache)
    {
        if (cache is null || cache.Count == 0)
        {
            return this with { FetchCache = EmptyCache };
        }

        return this with { FetchCache = new Dictionary<string, SuseFetchCacheEntry>(cache, StringComparer.OrdinalIgnoreCase) };
    }

    public SuseCursor WithProcessed(DateTimeOffset modified, IEnumerable<string> ids)
        => this with
        {
            LastModified = modified.ToUniversalTime(),
            ProcessedIds = ids?.Where(static id => !string.IsNullOrWhiteSpace(id))
                .Select(static id => id.Trim())
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToArray() ?? EmptyStringList
        };

    public bool TryGetCache(string key, out SuseFetchCacheEntry entry)
    {
        if (FetchCache.Count == 0)
        {
            entry = SuseFetchCacheEntry.Empty;
            return false;
        }

        return FetchCache.TryGetValue(key, out entry!);
    }

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

        var list = new List<string>(array.Count);
        foreach (var element in array)
        {
            if (element.BsonType == BsonType.String)
            {
                var str = element.AsString.Trim();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    list.Add(str);
                }
            }
        }

        return list;
    }

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

        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, SuseFetchCacheEntry> ReadCache(BsonDocument document)
    {
        if (!document.TryGetValue("fetchCache", out var value) || value is not BsonDocument cacheDocument || cacheDocument.ElementCount == 0)
        {
            return EmptyCache;
        }

        var cache = new Dictionary<string, SuseFetchCacheEntry>(StringComparer.OrdinalIgnoreCase);
        foreach (var element in cacheDocument.Elements)
        {
            if (element.Value is BsonDocument entry)
            {
                cache[element.Name] = SuseFetchCacheEntry.FromBson(entry);
            }
        }

        return cache;
    }
}
