using Microsoft.Extensions.DependencyInjection;
using RackPeek.Domain.Resources.Services.UseCases;
using Shared.Rcl.Commands;
using Spectre.Console;
using Spectre.Console.Cli;

namespace Shared.Rcl.Commands.Services;

public class ServiceDescribeCommand(
    IServiceProvider serviceProvider
) : AsyncCommand<ServiceNameSettings> {
    protected override async Task<int> ExecuteAsync(
        CommandContext context,
        ServiceNameSettings settings,
        CancellationToken cancellationToken) {
        using IServiceScope scope = serviceProvider.CreateScope();
        DescribeServiceUseCase useCase = scope.ServiceProvider.GetRequiredService<DescribeServiceUseCase>();

        ServiceDescription service = await useCase.ExecuteAsync(settings.Name);

        Grid grid = new Grid()
            .AddColumn(new GridColumn().NoWrap())
            .AddColumn(new GridColumn().NoWrap())
            .AddColumn(new GridColumn().NoWrap())
            .AddColumn(new GridColumn().NoWrap())
            .AddColumn(new GridColumn().NoWrap())
            .AddColumn(new GridColumn().NoWrap());

        grid.AddRow("Name:", service.Name.EscapeMarkup());
        grid.AddRow("Ip:", (service.Ip ?? "Unknown").EscapeMarkup());
        grid.AddRow("Port:", (service.Port?.ToString() ?? "Unknown").EscapeMarkup());
        grid.AddRow("Protocol:", (service.Protocol ?? "Unknown").EscapeMarkup());
        grid.AddRow("Url:", (service.Url ?? "Unknown").EscapeMarkup());
        grid.AddRow("Runs On:",
            ServicesFormatExtensions.FormatRunsOn(string.Join(", ", service.RunsOnSystemHost),
                string.Join(", ", service.RunsOnPhysicalHost)));

        if (service.Labels.Count > 0)
            grid.AddRow("Labels:", string.Join(", ", service.Labels.Select(kvp => $"{kvp.Key.EscapeMarkup()}: {kvp.Value.EscapeMarkup()}")));

        AnsiConsole.Write(
            new Panel(grid)
                .Header("Service")
                .Border(BoxBorder.Rounded));

        return 0;
    }
}
