using System.CommandLine;
using System.CommandLine.Parsing;

namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;

/// <summary>
/// Resolved Management API connection details for an <c>audit</c> subcommand, or an
/// error describing why resolution failed.
/// </summary>
public sealed class AuditConnection
{
    /// <summary>
    /// The management URL, or null if resolution failed.
    /// </summary>
    public string? Url { get; init; }

    /// <summary>
    /// The username for authentication, or null if resolution failed.
    /// </summary>
    public string? Username { get; init; }

    /// <summary>
    /// The password for authentication, or null if resolution failed.
    /// </summary>
    public string? Password { get; init; }

    /// <summary>
    /// Error message if resolution failed, or null.
    /// </summary>
    public string? Error { get; init; }

    /// <summary>
    /// Error code if resolution failed, or null.
    /// </summary>
    public string? ErrorCode { get; init; }

    /// <summary>
    /// Creates a failed connection with an error message and code.
    /// </summary>
    /// <param name="error">The error message.</param>
    /// <param name="code">The error code.</param>
    /// <returns>A failed AuditConnection.</returns>
    public static AuditConnection Fail(string error, string code)
        => new() { Error = error, ErrorCode = code };
}

/// <summary>
/// Connection/format resolution shared by the <c>audit</c> subcommands. Mirrors the URL
/// and credential precedence used by <see cref="CommandHelpers"/> (command line → config
/// file / environment), but produces a raw <see cref="ManagementHttpClient"/> target
/// because the audit endpoints are plain REST resources rather than <c>POST /management</c>
/// command-envelope calls.
/// </summary>
public static class AuditCommandHelpers
{
    /// <summary>
    /// Resolves management API connection details from command line arguments, config file, or environment variables.
    /// </summary>
    /// <param name="result">The parsed command line arguments.</param>
    /// <param name="urlOption">The URL option.</param>
    /// <param name="usernameOption">The username option.</param>
    /// <param name="passwordOption">The password option.</param>
    /// <returns>The resolved connection details, or a failure result.</returns>
    public static AuditConnection ResolveConnection(
        ParseResult result,
        Option<string> urlOption,
        Option<string> usernameOption,
        Option<string> 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 SCADABRIDGE_MANAGEMENT_URL, or add 'managementUrl' to ~/.scadabridge/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 SCADABRIDGE_USERNAME/SCADABRIDGE_PASSWORD.",
                "NO_CREDENTIALS");
        }

        return new AuditConnection { Url = url, Username = username, Password = password };
    }

    /// <summary>
    /// Resolves the output format from command line arguments, config file, or defaults to "table".
    /// </summary>
    /// <param name="result">The parsed command line arguments.</param>
    /// <param name="formatOption">The format option.</param>
    /// <returns>The resolved format string.</returns>
    public static string ResolveFormat(ParseResult result, Option<string> formatOption)
        => CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load());
}
