using System.IO;
using System.Linq;
using System.Text.Json;
using SilverOS.Welcome.Core.Apps;
using Xunit;

public class AppCatalogTests
{
    [Fact]
    public void Deserializes_a_catalog_entry()
    {
        var json = """
        { "id":"vscodium","name":"VSCodium","description":"Telemetry-free VS Code.",
          "source":{"winget":"VSCodium.VSCodium"},"group":"developer",
          "roles":["developer"],"defaultFor":["developer"],"configure":null }
        """;
        var e = JsonSerializer.Deserialize<AppCatalogEntry>(json, AppCatalogEntry.JsonOptions)!;
        Assert.Equal("vscodium", e.Id);
        Assert.Equal("VSCodium.VSCodium", e.Source.Winget);
        Assert.Contains("developer", e.Roles);
        Assert.Contains("developer", e.DefaultFor);
    }
}

public class AppCatalogLoaderTests
{
    static string WriteCatalog(string body)
    {
        var dir = Path.Combine(Path.GetTempPath(), "smcat-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(dir);
        File.WriteAllText(Path.Combine(dir, "catalog.json"), body);
        return dir;
    }

    const string Body = """
    { "schemaVersion":1, "apps":[
      {"id":"tb","name":"Thunderbird","source":{"winget":"Mozilla.Thunderbird"},"group":"essentials","roles":["essentials"],"defaultFor":["essentials"]},
      {"id":"vscodium","name":"VSCodium","source":{"winget":"VSCodium.VSCodium"},"group":"developer","roles":["developer"],"defaultFor":["developer"]},
      {"id":"rider","name":"Rider","source":{"winget":"JetBrains.Rider"},"group":"developer","roles":["developer"],"defaultFor":[]}
    ]}
    """;

    [Fact]
    public void AppsForRole_returns_essentials_plus_role()
    {
        var c = new AppCatalog().Load(WriteCatalog(Body));
        var ids = c.AppsForRole("developer").Select(a => a.Id).ToList();
        Assert.Contains("tb", ids);
        Assert.Contains("vscodium", ids);
        Assert.Contains("rider", ids);
    }

    [Fact]
    public void DefaultSelection_only_pre_checks_defaultFor()
    {
        var c = new AppCatalog().Load(WriteCatalog(Body));
        var def = c.DefaultSelectionForRole("developer");
        Assert.Contains("tb", def);
        Assert.Contains("vscodium", def);
        Assert.DoesNotContain("rider", def);
    }

    [Fact]
    public void Missing_catalog_returns_empty_not_throw()
    {
        var c = new AppCatalog().Load(Path.Combine(Path.GetTempPath(), "nope-" + Guid.NewGuid().ToString("N")));
        Assert.Empty(c.All);
    }
}
