using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.GRAccess.Cli.Session;

namespace ZB.MOM.WW.GRAccess.Cli.Commands.Session
{
    [Command("session stop", Description = "Stop the background GRAccess session")]
    public class SessionStopCommand : ICommand
    {
        [CommandOption("galaxy", 'g', Description = "Galaxy name", IsRequired = true)]
        public string GalaxyName { get; init; }

        public async ValueTask ExecuteAsync(IConsole console)
        {
            if (!SessionClient.TryConnect(GalaxyName, out var client))
            {
                await console.Output.WriteLineAsync("No active session found.").ConfigureAwait(false);
                return;
            }

            using (client)
            {
                var response = await client.SendShutdownAsync().ConfigureAwait(false);
                if (response.Success)
                    await console.Output.WriteLineAsync("Session stopped.").ConfigureAwait(false);
                else
                    await console.Error.WriteLineAsync($"Error stopping session: {response.Error}")
                        .ConfigureAwait(false);
            }
        }
    }
}
