using NetCord;
using NetCord.Rest;
using NetCord.Services.ApplicationCommands;

namespace GmRelay.DiscordBot.Features.Sessions;

public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandContext>
{
    private readonly DiscordListSessionsHandler _handler;

    public DiscordListSessionsCommand(DiscordListSessionsHandler handler)
    {
        _handler = handler;
    }

    [SlashCommand("listsessions", "Show upcoming game sessions in this server")]
    public async Task ExecuteAsync()
    {
        var guildId = Context.Interaction.GuildId?.ToString()
            ?? throw new InvalidOperationException("This command can only be used in a guild.");
        var channelId = Context.Channel.Id.ToString();
        var member = Context.User as GuildInteractionUser;
        var resolvedPermissions = member is null ? 0UL : (ulong)member.Permissions;
        var guildOwnerId = 0UL;

        var view = await _handler.BuildScheduleAsync(
            guildId,
            channelId,
            Context.User.Id,
            resolvedPermissions,
            guildOwnerId,
            CancellationToken.None);

        if (view is null)
        {
            await Context.Interaction.SendResponseAsync(
                InteractionCallback.Message("📭 В этом сервере нет предстоящих игр."));
            return;
        }

        var (embeds, actionRows) = Rendering.DiscordSessionBatchRenderer.Render(view);

        await Context.Interaction.SendResponseAsync(
            InteractionCallback.Message(new InteractionMessageProperties()
                .WithEmbeds(embeds)
                .WithComponents(actionRows)));
    }
}
