using MongoDB.Bson.Serialization.Attributes;

namespace StellaOps.Feedser.Storage.Mongo.PsirtFlags;

[BsonIgnoreExtraElements]
public sealed class PsirtFlagDocument
{
    [BsonId]
    [BsonElement("advisoryKey")]
    public string AdvisoryKey { get; set; } = string.Empty;

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

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

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

    [BsonElement("flaggedAt")]
    public DateTime FlaggedAt { get; set; }
}

internal static class PsirtFlagDocumentExtensions
{
    public static PsirtFlagDocument FromRecord(PsirtFlagRecord record)
    {
        ArgumentNullException.ThrowIfNull(record);

        return new PsirtFlagDocument
        {
            AdvisoryKey = string.IsNullOrWhiteSpace(record.AdvisoryKey) ? record.AdvisoryIdText : record.AdvisoryKey,
            Vendor = record.Vendor,
            SourceName = record.SourceName,
            AdvisoryIdText = record.AdvisoryIdText,
            FlaggedAt = record.FlaggedAt.UtcDateTime,
        };
    }

    public static PsirtFlagRecord ToRecord(this PsirtFlagDocument document)
    {
        ArgumentNullException.ThrowIfNull(document);

        return new PsirtFlagRecord(
            document.AdvisoryKey,
            document.Vendor,
            document.SourceName,
            document.AdvisoryIdText,
            DateTime.SpecifyKind(document.FlaggedAt, DateTimeKind.Utc));
    }
}
