using Telegram.Bot;
using Telegram.Bot.Types;

namespace GmRelay.Bot.Infrastructure.Telegram;

public sealed class TelegramMiniAppMenuButtonService(
    ITelegramBotClient bot,
    IConfiguration configuration,
    ILogger<TelegramMiniAppMenuButtonService> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var miniAppUrl = configuration["Telegram:MiniAppUrl"];
        if (string.IsNullOrWhiteSpace(miniAppUrl))
        {
            logger.LogInformation("Telegram Mini App URL is not configured; menu button setup skipped.");
            return;
        }

        if (!Uri.TryCreate(miniAppUrl, UriKind.Absolute, out var uri) ||
            (uri.Scheme != Uri.UriSchemeHttps && !uri.IsLoopback))
        {
            logger.LogWarning("Telegram Mini App URL {MiniAppUrl} is not a valid HTTPS URL.", miniAppUrl);
            return;
        }

        try
        {
            await bot.SetChatMenuButton(
                menuButton: new MenuButtonWebApp
                {
                    Text = "Dashboard",
                    WebApp = new WebAppInfo(miniAppUrl)
                },
                cancellationToken: cancellationToken);

            logger.LogInformation("Telegram Mini App menu button configured for {MiniAppUrl}.", miniAppUrl);
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "Failed to configure Telegram Mini App menu button.");
        }
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
