using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace StellaOps.Feedser.Storage.Mongo.Dtos;

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

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

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

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

    [BsonElement("payload")]
    public BsonDocument Payload { get; set; } = new();

    [BsonElement("validatedAt")]
    public DateTime ValidatedAt { get; set; }
}

internal static class DtoDocumentExtensions
{
    public static DtoDocument FromRecord(DtoRecord record)
        => new()
        {
            Id = record.Id.ToString(),
            DocumentId = record.DocumentId.ToString(),
            SourceName = record.SourceName,
            SchemaVersion = record.SchemaVersion,
            Payload = record.Payload ?? new BsonDocument(),
            ValidatedAt = record.ValidatedAt.UtcDateTime,
        };

    public static DtoRecord ToRecord(this DtoDocument document)
        => new(
            Guid.Parse(document.Id),
            Guid.Parse(document.DocumentId),
            document.SourceName,
            document.SchemaVersion,
            document.Payload,
            DateTime.SpecifyKind(document.ValidatedAt, DateTimeKind.Utc));
}
