using GmRelay.Bot.Infrastructure.Telegram;
using GmRelay.Shared.Domain;
using GmRelay.Shared.Features.Sessions.RescheduleSession;
using GmRelay.Shared.Platform;
using Telegram.Bot;

namespace GmRelay.Bot.Features.Sessions.RescheduleSession;

public sealed record HandleRescheduleVoteCommand(
    Guid OptionId,
    long TelegramUserId,
    string CallbackQueryId,
    long ChatId,
    int MessageId);

public sealed class HandleRescheduleVoteHandler(
    GmRelay.Shared.Features.Sessions.RescheduleSession.HandleRescheduleVoteHandler sharedHandler,
    ITelegramBotClient bot,
    IPlatformMessenger messenger,
    ILogger<HandleRescheduleVoteHandler> logger)
{
    public async Task HandleAsync(HandleRescheduleVoteCommand command, CancellationToken ct)
    {
        var platformUser = new PlatformUser(
            PlatformKind.Telegram,
            command.TelegramUserId.ToString(),
            string.Empty,
            null);

        var platformGroup = new PlatformGroup(
            PlatformKind.Telegram,
            command.ChatId.ToString(),
            string.Empty);

        var sharedCommand = new GmRelay.Shared.Features.Sessions.RescheduleSession.HandleRescheduleVoteCommand(
            command.OptionId,
            platformUser,
            platformGroup,
            command.CallbackQueryId,
            TelegramPlatformIds.Message(command.ChatId, null, command.MessageId));

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

        if (!result.Success)
        {
            await messenger.AnswerInteractionAsync(
                new PlatformInteractionReply(command.CallbackQueryId, result.ReplyText!, result.ReplyText!.Contains("дедлайн")),
                ct);
            return;
        }

        var voteText = HandleRescheduleTimeInputHandler.BuildVotingMessage(
            result.Title!,
            result.CurrentScheduledAt,
            result.VotingDeadlineAt,
            result.Options,
            result.Participants,
            result.Votes);
        var keyboard = HandleRescheduleTimeInputHandler.BuildVotingKeyboard(result.Options);

        try
        {
            await bot.EditMessageText(
                chatId: command.ChatId,
                messageId: command.MessageId,
                text: voteText,
                parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
                replyMarkup: keyboard,
                cancellationToken: ct);
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "Failed to update reschedule vote message for proposal {ProposalId}", result.ProposalId);
        }

        await messenger.AnswerInteractionAsync(
            new PlatformInteractionReply(command.CallbackQueryId, result.ReplyText!),
            ct);
    }
}
