using Spectre.Console;
using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets.Cli.Interactive.Flows;

/// <summary>
/// Shared prompt/console helpers reused across the CRUD flows: a re-prompting secret-name validator and
/// the CLI actor-stamp fallback. Centralized so the validation and audit-actor conventions stay identical
/// in every flow.
/// </summary>
internal static class FlowPrompts
{
    /// <summary>
    /// A <see cref="TextPrompt{T}"/> validation callback that accepts a raw name iff it is a legal
    /// <see cref="SecretName"/>, otherwise re-prompts with the constructor's own diagnostic. The
    /// diagnostic is <see cref="Markup.Escape(string)"/>d because it embeds bracketed text (e.g. the
    /// allowed-character class <c>[a-z0-9._/-]</c>) that Spectre would otherwise parse as markup and throw on.
    /// </summary>
    /// <param name="raw">The raw name entered at the prompt.</param>
    /// <returns>Success when <paramref name="raw"/> is a valid name; an escaped error otherwise.</returns>
    public static ValidationResult ValidateSecretName(string raw)
    {
        try
        {
            _ = new SecretName(raw);
            return ValidationResult.Success();
        }
        catch (ArgumentException ex)
        {
            return ValidationResult.Error(Markup.Escape(ex.Message));
        }
    }

    /// <summary>
    /// The principal recorded as <c>created_by</c>/<c>updated_by</c> for CLI-originated writes — the OS
    /// user name, or the literal <c>"cli"</c> when it is unavailable (mirrors <c>Program.cs</c>).
    /// </summary>
    public static string Actor =>
        string.IsNullOrWhiteSpace(Environment.UserName) ? "cli" : Environment.UserName;
}
