using System.Collections.Immutable;
using System.Linq;
using System.Text.Json.Serialization;

namespace StellaOps.Feedser.Models;

/// <summary>
/// Canonical advisory document produced after merge. Collections are pre-sorted for deterministic serialization.
/// </summary>
public sealed record Advisory
{
    public static Advisory Empty { get; } = new(
        advisoryKey: "unknown",
        title: "",
        summary: null,
        language: null,
        published: null,
        modified: null,
        severity: null,
        exploitKnown: false,
        aliases: Array.Empty<string>(),
        references: Array.Empty<AdvisoryReference>(),
        affectedPackages: Array.Empty<AffectedPackage>(),
        cvssMetrics: Array.Empty<CvssMetric>(),
        provenance: Array.Empty<AdvisoryProvenance>());

    public Advisory(
        string advisoryKey,
        string title,
        string? summary,
        string? language,
        DateTimeOffset? published,
        DateTimeOffset? modified,
        string? severity,
        bool exploitKnown,
        IEnumerable<string>? aliases,
        IEnumerable<AdvisoryReference>? references,
        IEnumerable<AffectedPackage>? affectedPackages,
        IEnumerable<CvssMetric>? cvssMetrics,
        IEnumerable<AdvisoryProvenance>? provenance)
    {
        AdvisoryKey = Validation.EnsureNotNullOrWhiteSpace(advisoryKey, nameof(advisoryKey));
        Title = Validation.EnsureNotNullOrWhiteSpace(title, nameof(title));
        Summary = Validation.TrimToNull(summary);
        Language = Validation.TrimToNull(language)?.ToLowerInvariant();
        Published = published?.ToUniversalTime();
        Modified = modified?.ToUniversalTime();
        Severity = SeverityNormalization.Normalize(severity);
        ExploitKnown = exploitKnown;

        Aliases = (aliases ?? Array.Empty<string>())
            .Select(static alias => Validation.TryNormalizeAlias(alias, out var normalized) ? normalized! : null)
            .Where(static alias => alias is not null)
            .Distinct(StringComparer.Ordinal)
            .OrderBy(static alias => alias, StringComparer.Ordinal)
            .Select(static alias => alias!)
            .ToImmutableArray();

        References = (references ?? Array.Empty<AdvisoryReference>())
            .Where(static reference => reference is not null)
            .OrderBy(static reference => reference.Url, StringComparer.Ordinal)
            .ThenBy(static reference => reference.Kind, StringComparer.Ordinal)
            .ThenBy(static reference => reference.SourceTag, StringComparer.Ordinal)
            .ThenBy(static reference => reference.Provenance.RecordedAt)
            .ToImmutableArray();

        AffectedPackages = (affectedPackages ?? Array.Empty<AffectedPackage>())
            .Where(static package => package is not null)
            .OrderBy(static package => package.Type, StringComparer.Ordinal)
            .ThenBy(static package => package.Identifier, StringComparer.Ordinal)
            .ThenBy(static package => package.Platform, StringComparer.Ordinal)
            .ToImmutableArray();

        CvssMetrics = (cvssMetrics ?? Array.Empty<CvssMetric>())
            .Where(static metric => metric is not null)
            .OrderBy(static metric => metric.Version, StringComparer.Ordinal)
            .ThenBy(static metric => metric.Vector, StringComparer.Ordinal)
            .ToImmutableArray();

        Provenance = (provenance ?? Array.Empty<AdvisoryProvenance>())
            .Where(static p => p is not null)
            .OrderBy(static p => p.Source, StringComparer.Ordinal)
            .ThenBy(static p => p.Kind, StringComparer.Ordinal)
            .ThenBy(static p => p.RecordedAt)
            .ToImmutableArray();
    }

    [JsonConstructor]
    public Advisory(
        string advisoryKey,
        string title,
        string? summary,
        string? language,
        DateTimeOffset? published,
        DateTimeOffset? modified,
        string? severity,
        bool exploitKnown,
        ImmutableArray<string> aliases,
        ImmutableArray<AdvisoryReference> references,
        ImmutableArray<AffectedPackage> affectedPackages,
        ImmutableArray<CvssMetric> cvssMetrics,
        ImmutableArray<AdvisoryProvenance> provenance)
        : this(
            advisoryKey,
            title,
            summary,
            language,
            published,
            modified,
            severity,
            exploitKnown,
            aliases.IsDefault ? null : aliases.AsEnumerable(),
            references.IsDefault ? null : references.AsEnumerable(),
            affectedPackages.IsDefault ? null : affectedPackages.AsEnumerable(),
            cvssMetrics.IsDefault ? null : cvssMetrics.AsEnumerable(),
            provenance.IsDefault ? null : provenance.AsEnumerable())
    {
    }

    public string AdvisoryKey { get; }

    public string Title { get; }

    public string? Summary { get; }

    public string? Language { get; }

    public DateTimeOffset? Published { get; }

    public DateTimeOffset? Modified { get; }

    public string? Severity { get; }

    public bool ExploitKnown { get; }

    public ImmutableArray<string> Aliases { get; }

    public ImmutableArray<AdvisoryReference> References { get; }

    public ImmutableArray<AffectedPackage> AffectedPackages { get; }

    public ImmutableArray<CvssMetric> CvssMetrics { get; }

    public ImmutableArray<AdvisoryProvenance> Provenance { get; }
}
