using NATS.Server.Auth;

namespace NATS.Server.Imports;

public sealed class ImportMap
{
    public List<StreamImport> Streams { get; } = [];
    public Dictionary<string, List<ServiceImport>> Services { get; } = new(StringComparer.Ordinal);

    public void AddServiceImport(ServiceImport si)
    {
        if (!Services.TryGetValue(si.From, out var list))
        {
            list = [];
            Services[si.From] = list;
        }

        list.Add(si);
    }

    /// <summary>
    /// Returns the distinct set of source accounts referenced by stream imports.
    /// Go reference: accounts.go imports.streams — each streamImport has an acc field.
    /// </summary>
    public IReadOnlyList<Account> GetStreamImportSourceAccounts()
    {
        if (Streams.Count == 0)
            return [];

        var seen = new HashSet<string>(StringComparer.Ordinal);
        var result = new List<Account>(Streams.Count);
        foreach (var si in Streams)
        {
            if (seen.Add(si.SourceAccount.Name))
                result.Add(si.SourceAccount);
        }
        return result;
    }
}
