using System.Collections.Frozen;

namespace ScadaLink.Commons.Messages.Management;

public static class ManagementCommandRegistry
{
    private static readonly FrozenDictionary<string, Type> Commands = BuildRegistry();

    public static Type? Resolve(string commandName)
    {
        return Commands.GetValueOrDefault(commandName);
    }

    public static string GetCommandName(Type commandType)
    {
        var name = commandType.Name;
        return name.EndsWith("Command", StringComparison.Ordinal)
            ? name[..^"Command".Length]
            : name;
    }

    private static FrozenDictionary<string, Type> BuildRegistry()
    {
        var ns = typeof(ManagementEnvelope).Namespace!;
        var assembly = typeof(ManagementEnvelope).Assembly;

        return assembly.GetTypes()
            .Where(t => t.Namespace == ns
                && t.Name.EndsWith("Command", StringComparison.Ordinal)
                && !t.IsAbstract)
            .ToFrozenDictionary(
                t => t.Name[..^"Command".Length],
                t => t,
                StringComparer.OrdinalIgnoreCase);
    }
}
