using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using StellaOps.Feedser.Source.Distro.Suse.Internal;
using Xunit;

namespace StellaOps.Feedser.Source.Distro.Suse.Tests;

public sealed class SuseCsafParserTests
{
    [Fact]
    public void Parse_ProducesRecommendedAndAffectedPackages()
    {
        var json = ReadFixture("Source/Distro/Suse/Fixtures/suse-su-2025_0001-1.json");
        var dto = SuseCsafParser.Parse(json);

        Assert.Equal("SUSE-SU-2025:0001-1", dto.AdvisoryId);
        Assert.Contains("CVE-2025-0001", dto.CveIds);
        var package = Assert.Single(dto.Packages);
        Assert.Equal("openssl", package.Package);
        Assert.Equal("resolved", package.Status);
        Assert.NotNull(package.FixedVersion);
        Assert.Equal("SUSE Linux Enterprise Server 15 SP5", package.Platform);
        Assert.Equal("openssl-1.1.1w-150500.17.25.1.x86_64", package.CanonicalNevra);
    }

    [Fact]
    public void Parse_HandlesOpenInvestigation()
    {
        var json = ReadFixture("Source/Distro/Suse/Fixtures/suse-su-2025_0002-1.json");
        var dto = SuseCsafParser.Parse(json);

        Assert.Equal("SUSE-SU-2025:0002-1", dto.AdvisoryId);
        Assert.Contains("CVE-2025-0002", dto.CveIds);
        var package = Assert.Single(dto.Packages);
        Assert.Equal("open", package.Status);
        Assert.Equal("postgresql16", package.Package);
        Assert.NotNull(package.LastAffectedVersion);
    }

    private static string ReadFixture(string relativePath)
    {
        var path = Path.Combine(AppContext.BaseDirectory, relativePath.Replace('/', Path.DirectorySeparatorChar));
        if (!File.Exists(path))
        {
            throw new FileNotFoundException($"Fixture '{relativePath}' not found.", path);
        }

        return File.ReadAllText(path);
    }
}
