using GmRelay.Shared.Platform;
using Telegram.Bot.Types;

namespace GmRelay.Bot.Features.Sessions.ListSessions;

public sealed class ListSessionsHandler(
    GmRelay.Shared.Features.Sessions.ListSessions.ListSessionsHandler sharedHandler,
    IPlatformMessenger messenger)
{
    public async Task HandleAsync(Message message, CancellationToken cancellationToken)
    {
        var command = new GmRelay.Shared.Features.Sessions.ListSessions.ListSessionsCommand(
            new PlatformGroup(
                PlatformKind.Telegram,
                message.Chat.Id.ToString(),
                message.Chat.Title ?? "Private Chat",
                message.MessageThreadId?.ToString()),
            new PlatformUser(
                PlatformKind.Telegram,
                message.From?.Id.ToString() ?? string.Empty,
                message.From?.FirstName ?? string.Empty,
                message.From?.Username));

        var result = await sharedHandler.HandleAsync(command, cancellationToken);

        if (result.Sessions.Count == 0)
        {
            await messenger.SendGroupMessageAsync(command.Group, "📭 В этой группе нет предстоящих игр.", cancellationToken);
            return;
        }

        var text = SessionListMessageRenderer.RenderText(result.Sessions);
        var actions = result.CanManage ? SessionListMessageRenderer.RenderActions(result.Sessions) : [];

        await messenger.SendGroupMessageAsync(command.Group, text, actions, cancellationToken);
    }
}
