using System;
using System.Text.Json;

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

internal readonly record struct RedHatSummaryItem(string AdvisoryId, DateTimeOffset ReleasedOn, Uri ResourceUri)
{
    private static readonly string[] AdvisoryFields =
    {
        "RHSA",
        "RHBA",
        "RHEA",
        "RHUI",
        "RHBG",
        "RHBO",
        "advisory"
    };

    public static bool TryParse(JsonElement element, out RedHatSummaryItem item)
    {
        item = default;

        string? advisoryId = null;
        foreach (var field in AdvisoryFields)
        {
            if (element.TryGetProperty(field, out var advisoryProperty) && advisoryProperty.ValueKind == JsonValueKind.String)
            {
                var candidate = advisoryProperty.GetString();
                if (!string.IsNullOrWhiteSpace(candidate))
                {
                    advisoryId = candidate.Trim();
                    break;
                }
            }
        }

        if (string.IsNullOrWhiteSpace(advisoryId))
        {
            return false;
        }

        if (!element.TryGetProperty("released_on", out var releasedProperty) || releasedProperty.ValueKind != JsonValueKind.String)
        {
            return false;
        }

        if (!DateTimeOffset.TryParse(releasedProperty.GetString(), out var releasedOn))
        {
            return false;
        }

        if (!element.TryGetProperty("resource_url", out var resourceProperty) || resourceProperty.ValueKind != JsonValueKind.String)
        {
            return false;
        }

        var resourceValue = resourceProperty.GetString();
        if (!Uri.TryCreate(resourceValue, UriKind.Absolute, out var resourceUri))
        {
            return false;
        }

        item = new RedHatSummaryItem(advisoryId!, releasedOn.ToUniversalTime(), resourceUri);
        return true;
    }
}
