using BrassAndSigil.Server.Models;
using Spectre.Console;
using Spectre.Console.Cli;

namespace BrassAndSigil.Server.Commands;

/// <summary>
/// Set or rotate the web panel admin password from the CLI.
/// Useful when first-time-setting up before exposing the panel publicly,
/// or rotating after a suspected leak without going through the panel UI.
/// </summary>
public sealed class SetPasswordCommand : Command<BaseCommandSettings>
{
    public override int Execute(CommandContext context, BaseCommandSettings settings)
    {
        var config = ServerConfig.Load(settings.ConfigPath);

        if (Console.IsInputRedirected)
        {
            AnsiConsole.MarkupLine("[red]set-password requires an interactive terminal.[/]");
            return 1;
        }

        AnsiConsole.MarkupLine("[bold]Set admin password[/]");
        if (!string.IsNullOrEmpty(config.WebPassword))
            AnsiConsole.MarkupLine("[grey]An existing password is already set; this will overwrite it.[/]");

        string pw1, pw2;
        while (true)
        {
            pw1 = AnsiConsole.Prompt(new TextPrompt<string>("New password (min 8 chars):").Secret());
            if (pw1.Length < 8) { AnsiConsole.MarkupLine("[red]Too short.[/]"); continue; }
            pw2 = AnsiConsole.Prompt(new TextPrompt<string>("Confirm:").Secret());
            if (pw1 != pw2) { AnsiConsole.MarkupLine("[red]Doesn't match.[/]"); continue; }
            break;
        }

        config.WebPassword = pw1;
        config.Save(settings.ConfigPath);
        AnsiConsole.MarkupLine($"[green]✓[/] Saved to {settings.ConfigPath}.");
        AnsiConsole.MarkupLine("[grey]Restart the server for the new password to take effect.[/]");
        return 0;
    }
}
