using AiLogia.Bot.Services;
using Microsoft.Extensions.Configuration;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace AiLogia.Bot.Handlers;

public interface ICanHandle
{
    bool CanHandle(Message message);
}

public class FeedbackMessageHandler : IMessageHandler, ICanHandle
{
    private static readonly HashSet<MessageType> ServiceTypes = new()
    {
        MessageType.NewChatMembers,
        MessageType.LeftChatMember,
        MessageType.NewChatTitle,
        MessageType.NewChatPhoto,
        MessageType.DeleteChatPhoto,
        MessageType.GroupChatCreated,
        MessageType.SupergroupChatCreated,
        MessageType.ChannelChatCreated,
        MessageType.MigrateFromChatId,
        MessageType.MigrateToChatId,
        MessageType.MessageAutoDeleteTimerChanged,
        MessageType.ProximityAlertTriggered,
        MessageType.WebAppData,
        MessageType.VideoChatScheduled,
        MessageType.VideoChatStarted,
        MessageType.VideoChatEnded,
        MessageType.VideoChatParticipantsInvited,
        MessageType.ForumTopicCreated,
        MessageType.ForumTopicClosed,
        MessageType.ForumTopicReopened,
        MessageType.ForumTopicEdited,
        MessageType.GeneralForumTopicHidden,
        MessageType.GeneralForumTopicUnhidden,
        MessageType.WriteAccessAllowed,
        MessageType.UsersShared,
        MessageType.ChatShared,
        MessageType.ChatBackgroundSet,
        MessageType.PassportData,
        MessageType.Invoice,
        MessageType.SuccessfulPayment,
        MessageType.RefundedPayment,
        MessageType.PaidMedia,
        MessageType.PaidMessagePriceChanged,
        MessageType.SuggestedPostApproved,
        MessageType.SuggestedPostApprovalFailed,
        MessageType.SuggestedPostDeclined,
        MessageType.SuggestedPostPaid,
        MessageType.SuggestedPostRefunded,
        MessageType.Checklist,
        MessageType.ChecklistTasksDone,
        MessageType.ChecklistTasksAdded,
        MessageType.DirectMessagePriceChanged,
        MessageType.GiveawayCreated,
        MessageType.Giveaway,
        MessageType.GiveawayWinners,
        MessageType.GiveawayCompleted,
        MessageType.Story, // спорный: можно убрать из ServiceTypes, если хочешь пробовать форвард
        // MessageType.ConnectedWebsite — обычно сервисное
        MessageType.ConnectedWebsite
    };

    private readonly ITelegramBotClient _bot;
    private readonly IFeedbackStateService _state;
    private readonly long _adminChatId;
    private readonly string _botName;

    public FeedbackMessageHandler(
        ITelegramBotClient bot,
        IFeedbackStateService state,
        IConfiguration cfg)
    {
        _bot = bot;
        _state = state;
        _adminChatId = cfg.GetValue<long>("AdminChatId");
        _botName = "@" + cfg.GetValue<string>("BotTgName");
    }

    public bool CanHandle(Message msg)
    {
        if (msg?.From == null) return false;
        if (!_state.IsEnabled(msg.From.Id)) return false;

        // игнорим служебные типы и экзотику
        return !ServiceTypes.Contains(msg.Type);
    }


    public async Task HandleAsync(Message msg)
    {
        var user = msg.From!;
        var fromChat = msg.Chat.Id;

        // 1) служебная шапка (кто прислал)
        var header =
            $"Фидбек из {_botName}\n" +
            $"• UserId: `{user.Id}`\n" +
            $"• User: {(string.IsNullOrEmpty(user.Username) ? $"{user.FirstName} {user.LastName}".Trim() : "@" + user.Username)}";

        await _bot.SendMessage(
            chatId: _adminChatId,
            text: header,
            //parseMode: ParseMode.Markdown,
            disableNotification: true);

        // 2) собственно форвард
        await _bot.ForwardMessage(
            chatId: _adminChatId,
            fromChatId: fromChat,
            messageId: msg.MessageId);

        // 3) подтверждение пользователю и выход из режима
        _state.Disable(user.Id);

        await _bot.SendMessage(
            chatId: fromChat,
            text: "Спасибо! Я передал сообщение команде 👌",
            parseMode: ParseMode.Markdown);
    }
}