namespace GmRelay.Bot.Tests.Infrastructure.Telegram;

public sealed class TelegramMiniAppEntryPointTests
{
    [Fact]
    public async Task UpdateRouter_ShouldExposeMiniAppButtonInStartCommand()
    {
        var updateRouter = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs"));

        Assert.Contains("Telegram:MiniAppUrl", updateRouter, StringComparison.Ordinal);
        Assert.Contains("InlineKeyboardButton.WithWebApp", updateRouter, StringComparison.Ordinal);
        Assert.Contains("Открыть dashboard", updateRouter, StringComparison.Ordinal);
    }

    [Fact]
    public async Task BotStartup_ShouldRegisterMiniAppMenuButtonService()
    {
        var program = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Program.cs"));

        Assert.Contains("TelegramMiniAppMenuButtonService", program, StringComparison.Ordinal);
        Assert.Contains("AddHostedService<TelegramMiniAppMenuButtonService>", program, StringComparison.Ordinal);
    }

    [Fact]
    public async Task MiniAppMenuButtonService_ShouldSetTelegramWebAppMenuButtonWhenConfigured()
    {
        var service = await File.ReadAllTextAsync(FindRepositoryFile("src/GmRelay.Bot/Infrastructure/Telegram/TelegramMiniAppMenuButtonService.cs"));

        Assert.Contains("SetChatMenuButton", service, StringComparison.Ordinal);
        Assert.Contains("MenuButtonWebApp", service, StringComparison.Ordinal);
        Assert.Contains("Telegram:MiniAppUrl", service, StringComparison.Ordinal);
    }

    private static string FindRepositoryFile(string relativePath)
    {
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null)
        {
            var candidate = Path.Combine(directory.FullName, relativePath);
            if (File.Exists(candidate))
            {
                return candidate;
            }

            directory = directory.Parent;
        }

        throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
    }
}
