using System.CommandLine;
using System.CommandLine.Parsing;
namespace ScadaLink.CLI.Commands;
///
/// Resolved Management API connection details for an audit subcommand, or an
/// error describing why resolution failed.
///
public sealed class AuditConnection
{
public string? Url { get; init; }
public string? Username { get; init; }
public string? Password { get; init; }
public string? Error { get; init; }
public string? ErrorCode { get; init; }
public static AuditConnection Fail(string error, string code)
=> new() { Error = error, ErrorCode = code };
}
///
/// Connection/format resolution shared by the audit subcommands. Mirrors the URL
/// and credential precedence used by (command line → config
/// file / environment), but produces a raw target
/// because the audit endpoints are plain REST resources rather than POST /management
/// command-envelope calls.
///
public static class AuditCommandHelpers
{
public static AuditConnection ResolveConnection(
ParseResult result,
Option urlOption,
Option usernameOption,
Option passwordOption)
{
var config = CliConfig.Load();
var url = result.GetValue(urlOption);
if (string.IsNullOrWhiteSpace(url))
url = config.ManagementUrl;
if (string.IsNullOrWhiteSpace(url))
{
return AuditConnection.Fail(
"No management URL specified. Use --url, set SCADALINK_MANAGEMENT_URL, or add 'managementUrl' to ~/.scadalink/config.json.",
"NO_URL");
}
if (!CommandHelpers.IsValidManagementUrl(url))
{
return AuditConnection.Fail(
$"Invalid management URL '{url}'. Expected an absolute http/https URL (e.g. http://localhost:9001).",
"INVALID_URL");
}
var username = CommandHelpers.ResolveCredential(result.GetValue(usernameOption), config.Username);
var password = CommandHelpers.ResolveCredential(result.GetValue(passwordOption), config.Password);
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
return AuditConnection.Fail(
"Credentials required. Use --username/--password or set SCADALINK_USERNAME/SCADALINK_PASSWORD.",
"NO_CREDENTIALS");
}
return new AuditConnection { Url = url, Username = username, Password = password };
}
public static string ResolveFormat(ParseResult result, Option formatOption)
=> CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load());
}