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

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

/// <summary>
/// Soft-deletes (tombstones) a secret after an explicit confirmation. Tombstoning only rewrites metadata
/// columns — it never touches ciphertext — so it needs no KEK and runs on a degraded session. A declined
/// confirmation leaves the row untouched; a confirmed delete reports whether a matching row was found.
/// </summary>
public sealed class DeleteSecretFlow : IInteractiveFlow
{
    /// <inheritdoc />
    public string Title => "Delete a secret";

    /// <inheritdoc />
    public bool RequiresKek => false;

    /// <inheritdoc />
    public async Task RunAsync(IAnsiConsole console, SecretsSession session, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(console);
        ArgumentNullException.ThrowIfNull(session);

        var name = new SecretName(console.Prompt(
            new TextPrompt<string>("Secret [green]name[/]:").Validate(FlowPrompts.ValidateSecretName)));

        // Check existence first, so an unknown name is reported without a pointless confirm prompt.
        StoredSecret? existing = await session.Store.GetAsync(name, ct).ConfigureAwait(false);
        if (existing is null || existing.IsDeleted)
        {
            console.MarkupLineInterpolated($"[red]No secret named '{name.Value}'.[/]");
            return;
        }

        if (!console.Prompt(new ConfirmationPrompt($"Delete (tombstone) '{name.Value}'?") { DefaultValue = false }))
        {
            console.MarkupLine("[yellow]Left in place.[/]");
            return;
        }

        bool removed = await session.Store.DeleteAsync(name, FlowPrompts.Actor, ct).ConfigureAwait(false);

        console.MarkupLine(removed
            ? $"[green]Tombstoned '{Markup.Escape(name.Value)}'.[/]"
            : $"[red]No secret named '{Markup.Escape(name.Value)}'.[/]");
    }
}
