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

namespace StellaOps.Feedser.Storage.Mongo.MergeEvents;

[BsonIgnoreExtraElements]
public sealed class MergeEventDocument
{
    [BsonId]
    public string Id { get; set; } = string.Empty;

    [BsonElement("advisoryKey")]
    public string AdvisoryKey { get; set; } = string.Empty;

    [BsonElement("beforeHash")]
    public byte[] BeforeHash { get; set; } = Array.Empty<byte>();

    [BsonElement("afterHash")]
    public byte[] AfterHash { get; set; } = Array.Empty<byte>();

    [BsonElement("mergedAt")]
    public DateTime MergedAt { get; set; }

    [BsonElement("inputDocuments")]
    public List<string> InputDocuments { get; set; } = new();
}

internal static class MergeEventDocumentExtensions
{
    public static MergeEventDocument FromRecord(MergeEventRecord record)
        => new()
        {
            Id = record.Id.ToString(),
            AdvisoryKey = record.AdvisoryKey,
            BeforeHash = record.BeforeHash,
            AfterHash = record.AfterHash,
            MergedAt = record.MergedAt.UtcDateTime,
            InputDocuments = record.InputDocumentIds.Select(static id => id.ToString()).ToList(),
        };

    public static MergeEventRecord ToRecord(this MergeEventDocument document)
        => new(
            Guid.Parse(document.Id),
            document.AdvisoryKey,
            document.BeforeHash,
            document.AfterHash,
            DateTime.SpecifyKind(document.MergedAt, DateTimeKind.Utc),
            document.InputDocuments.Select(static value => Guid.Parse(value)).ToList());
}
