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

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

/// <summary>
/// Lists the safe metadata projection of every live secret as a table — name, content type, KEK id,
/// revision, last-updated stamp, and updater. It renders only <see cref="SecretMetadata"/> (which carries
/// no ciphertext or plaintext), needs no KEK, and never decrypts, so it is the one CRUD flow that runs on
/// a degraded session.
/// </summary>
public sealed class ListSecretsFlow : IInteractiveFlow
{
    /// <inheritdoc />
    public string Title => "List secrets";

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

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

        IReadOnlyList<SecretMetadata> items =
            await session.Store.ListAsync(includeDeleted: false, ct).ConfigureAwait(false);

        if (items.Count == 0)
        {
            console.MarkupLine("[grey](none)[/]");
            return;
        }

        var table = new Table()
            .AddColumn("Name")
            .AddColumn("ContentType")
            .AddColumn("KekId")
            .AddColumn("Revision")
            .AddColumn("Updated")
            .AddColumn("UpdatedBy");

        foreach (SecretMetadata m in items)
        {
            table.AddRow(
                Markup.Escape(m.Name.Value),
                Markup.Escape(m.ContentType.ToString()),
                Markup.Escape(m.KekId),
                m.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),
                Markup.Escape(m.UpdatedUtc.ToString("u", System.Globalization.CultureInfo.InvariantCulture)),
                Markup.Escape(m.UpdatedBy ?? "—"));
        }

        console.Write(table);
    }
}
