using System.Text.Json;
using StellaOps.Feedser.Models;
using StellaOps.Feedser.Source.Nvd.Internal;
using StellaOps.Feedser.Storage.Mongo.Documents;

namespace StellaOps.Feedser.Source.Nvd.Tests;

public sealed class NvdConflictFixtureTests
{
    [Fact]
    public void ConflictFixture_MatchesSnapshot()
    {
        const string payload = """
        {
          "vulnerabilities": [
            {
              "cve": {
                "id": "CVE-2025-4242",
                "published": "2025-03-01T10:15:00Z",
                "lastModified": "2025-03-03T09:45:00Z",
                "descriptions": [
                  { "lang": "en", "value": "NVD baseline summary for conflict-package allowing container escape." }
                ],
                "references": [
                  {
                    "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-4242",
                    "source": "NVD",
                    "tags": ["Vendor Advisory"]
                  }
                ],
                "weaknesses": [
                  {
                    "description": [
                      { "lang": "en", "value": "CWE-269" }
                    ]
                  }
                ],
                "metrics": {
                  "cvssMetricV31": [
                    {
                      "cvssData": {
                        "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
                        "baseScore": 9.8,
                        "baseSeverity": "CRITICAL"
                      },
                      "exploitabilityScore": 3.9,
                      "impactScore": 5.9
                    }
                  ]
                },
                "configurations": {
                  "nodes": [
                    {
                      "cpeMatch": [
                        {
                          "criteria": "cpe:2.3:a:conflict:package:1.0:*:*:*:*:*:*:*",
                          "vulnerable": true,
                          "versionStartIncluding": "1.0",
                          "versionEndExcluding": "1.4"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          ]
        }
        """;

        using var document = JsonDocument.Parse(payload);

        var sourceDocument = new DocumentRecord(
            Id: Guid.Parse("1a6a0700-2dd0-4f69-bb37-64ca77e51c91"),
            SourceName: NvdConnectorPlugin.SourceName,
            Uri: "https://services.nvd.nist.gov/rest/json/cve/2.0?cveId=CVE-2025-4242",
            FetchedAt: new DateTimeOffset(2025, 3, 3, 10, 0, 0, TimeSpan.Zero),
            Sha256: "sha256-nvd-conflict-fixture",
            Status: "completed",
            ContentType: "application/json",
            Headers: null,
            Metadata: null,
            Etag: "\"etag-nvd-conflict\"",
            LastModified: new DateTimeOffset(2025, 3, 3, 9, 45, 0, TimeSpan.Zero),
            GridFsId: null);

        var advisories = NvdMapper.Map(document, sourceDocument, new DateTimeOffset(2025, 3, 4, 2, 0, 0, TimeSpan.Zero));
        var advisory = Assert.Single(advisories);

        var snapshot = SnapshotSerializer.ToSnapshot(advisory).Replace("\r\n", "\n").TrimEnd();
        var expectedPath = Path.Combine(AppContext.BaseDirectory, "Nvd", "Fixtures", "conflict-nvd.canonical.json");
        var expected = File.ReadAllText(expectedPath).Replace("\r\n", "\n").TrimEnd();

        if (!string.Equals(expected, snapshot, StringComparison.Ordinal))
        {
            var actualPath = Path.Combine(AppContext.BaseDirectory, "Nvd", "Fixtures", "conflict-nvd.canonical.actual.json");
            Directory.CreateDirectory(Path.GetDirectoryName(actualPath)!);
            File.WriteAllText(actualPath, snapshot);
        }

        Assert.Equal(expected, snapshot);
    }
}
