using AiLogia.Bot.Data;
using AiLogia.Bot.Diagnostics;
using AiLogia.Bot.Services;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;

namespace AiLogia.Bot.Handlers;

public class TestSelectedHandler(ITelegramBotClient bot, ISystemLogService log, IUserActionTracker tracker, ITestsRepository repo) : ICallbackHandler
{
    private readonly ITelegramBotClient _bot = bot;
    private readonly ISystemLogService _log = log;
    private readonly IUserActionTracker _tracker = tracker;
    private readonly ITestsRepository _repo = repo;

    public bool CanHandle(string data)
    {
        return data.StartsWith("test:");
    }

    public async Task HandleAsync(CallbackQuery callback)
    {
        await _tracker.TrackCallbackAsync("callback:test_selected", callback);

        var chatId = callback.Message?.Chat.Id ?? callback.From.Id;

        if (!int.TryParse(callback.Data?.Split(':')[1], out var testId))
        {
            await _bot.SendMessage(chatId, "❌ Неверный формат данных теста.");
            return;
        }

        var test = await _repo.GetTestByIdAsync(testId);
        if (test == null)
        {
            await _bot.SendMessage(chatId, "❌ Тест не найден или недоступен.");
            return;
        }

        var text = $"🧪 *{test.Title}*\n\n" +
                   $"{test.Description ?? "Описание отсутствует."}";

        text += "\n\nПриступаем?\n";

        var markup = new InlineKeyboardMarkup(new[]
        {
            InlineKeyboardButton.WithCallbackData("🚀 Да, начнем!", $"start:{test.Id}")
        });

        await _bot.SendMessage(
            chatId: chatId,
            text: text,
            parseMode: ParseMode.Markdown,
            replyMarkup: markup
        );
    }
}
