using GmRelay.DiscordBot.Rendering;
using GmRelay.Shared.Features.Sessions.RescheduleSession;
using GmRelay.Shared.Platform;
using NetCord.Rest;

namespace GmRelay.DiscordBot.Features.Sessions;

public sealed record DiscordRescheduleVoteInput(
    Guid OptionId,
    ulong UserId,
    string InteractionId,
    string GuildId,
    string ChannelId,
    string MessageId);

public sealed class DiscordRescheduleVoteHandler(
    GmRelay.Shared.Features.Sessions.RescheduleSession.HandleRescheduleVoteHandler sharedHandler,
    RestClient restClient,
    ILogger<DiscordRescheduleVoteHandler> logger)
{
    public async Task<string> HandleAsync(DiscordRescheduleVoteInput input, CancellationToken ct)
    {
        var command = new HandleRescheduleVoteCommand(
            input.OptionId,
            new PlatformUser(PlatformKind.Discord, input.UserId.ToString(), string.Empty, null),
            new PlatformGroup(PlatformKind.Discord, input.GuildId, string.Empty, input.ChannelId),
            input.InteractionId,
            new PlatformMessageRef(PlatformKind.Discord, input.ChannelId, null, input.MessageId));

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

        if (!result.Success)
        {
            return result.ReplyText!;
        }

        var (embed, actionRow) = DiscordRescheduleVotingRenderer.Render(
            result.Title!,
            result.CurrentScheduledAt,
            result.VotingDeadlineAt,
            result.Options,
            result.Participants,
            result.Votes);

        var channelIdUlong = ulong.Parse(input.ChannelId);
        var messageIdUlong = ulong.Parse(input.MessageId);

        try
        {
            await restClient.ModifyMessageAsync(channelIdUlong, messageIdUlong, options =>
            {
                options.Embeds = new[] { embed };
                options.Components = new[] { actionRow };
            });
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "Failed to update Discord vote message for proposal {ProposalId}", result.ProposalId);
        }

        return result.ReplyText!;
    }
}
