using System;
using System.Collections.Generic;
using StellaOps.Feedser.Storage.Mongo.Documents;

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

internal sealed record AdobeDocumentMetadata(
    string AdvisoryId,
    string? Title,
    DateTimeOffset? PublishedUtc,
    Uri DetailUri)
{
    private const string AdvisoryIdKey = "advisoryId";
    private const string TitleKey = "title";
    private const string PublishedKey = "published";

    public static AdobeDocumentMetadata FromDocument(DocumentRecord document)
    {
        ArgumentNullException.ThrowIfNull(document);

        if (document.Metadata is null)
        {
            throw new InvalidOperationException("Adobe document metadata is missing.");
        }

        var advisoryId = document.Metadata.TryGetValue(AdvisoryIdKey, out var idValue) ? idValue : null;
        if (string.IsNullOrWhiteSpace(advisoryId))
        {
            throw new InvalidOperationException("Adobe document advisoryId metadata missing.");
        }

        var title = document.Metadata.TryGetValue(TitleKey, out var titleValue) ? titleValue : null;
        DateTimeOffset? published = null;
        if (document.Metadata.TryGetValue(PublishedKey, out var publishedValue)
            && DateTimeOffset.TryParse(publishedValue, out var parsedPublished))
        {
            published = parsedPublished.ToUniversalTime();
        }

        if (!Uri.TryCreate(document.Uri, UriKind.Absolute, out var detailUri))
        {
            throw new InvalidOperationException("Adobe document URI invalid.");
        }

        return new AdobeDocumentMetadata(advisoryId.Trim(), string.IsNullOrWhiteSpace(title) ? null : title.Trim(), published, detailUri);
    }
}
