using System.Text.Json;
namespace ApiRegistrationTool;
///
/// Builds the Module → gateway short-code prefix map by reading
/// GB5Build/GB5Build/appsettings.json (ReverseProxy:Routes) at runtime.
///
/// Route entries look like:
/// "Accounts-route": { "Match": { "Path": "/as/{**catch-all}" }, ... }
///
/// Module name = route key with the "-route" suffix stripped.
/// Prefix = first path segment of Match.Path.
///
/// Adding support for a new module is just adding its route to the gateway's
/// appsettings.json — nothing here needs to change.
///
public sealed class ModulePrefixResolver
{
private readonly Dictionary _map;
private ModulePrefixResolver(Dictionary map) => _map = map;
public static ModulePrefixResolver Load(string gatewayAppSettingsPath)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
if (!File.Exists(gatewayAppSettingsPath))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($" [WARN] Gateway appsettings not found at {gatewayAppSettingsPath} — " +
"module prefixes will fall back to lowercased module names.");
Console.ResetColor();
return new ModulePrefixResolver(map);
}
using var stream = File.OpenRead(gatewayAppSettingsPath);
using var doc = JsonDocument.Parse(stream);
if (!doc.RootElement.TryGetProperty("ReverseProxy", out var reverseProxy) ||
!reverseProxy.TryGetProperty("Routes", out var routes))
{
return new ModulePrefixResolver(map);
}
foreach (var route in routes.EnumerateObject())
{
string key = route.Name;
if (!key.EndsWith("-route", StringComparison.OrdinalIgnoreCase)) continue;
string module = key[..^"-route".Length];
if (!route.Value.TryGetProperty("Match", out var match) ||
!match.TryGetProperty("Path", out var pathProp)) continue;
string? path = pathProp.GetString();
if (string.IsNullOrWhiteSpace(path)) continue;
string prefix = "/" + path.TrimStart('/').Split('/', 2)[0];
if (prefix.Length <= 1) continue;
map[module] = prefix;
}
return new ModulePrefixResolver(map);
}
/// Returns the gateway prefix for a module, or a lowercased fallback if unmapped.
public string GetPrefix(string module)
{
if (_map.TryGetValue(module, out var prefix)) return prefix;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($" [WARN] No gateway route found for module '{module}' — " +
$"add a \"{module}-route\" entry to GB5Build/appsettings.json. " +
$"Falling back to '/{module.ToLowerInvariant()}'.");
Console.ResetColor();
return "/" + module.ToLowerInvariant();
}
}