using GmRelay.DiscordBot.Infrastructure.Discord;
using GmRelay.Shared.Platform;
using GmRelay.Shared.Rendering;

namespace GmRelay.Bot.Tests.Discord;

public sealed class DiscordPlatformMessengerTests
{
    [Fact]
    public void Constructor_ShouldAcceptRestClientAndReplyCache()
    {
        var constructor = typeof(DiscordPlatformMessenger).GetConstructor(new[]
        {
            typeof(NetCord.Rest.RestClient),
            typeof(DiscordInteractionReplyCache)
        });
        Assert.NotNull(constructor);
    }

    [Fact]
    public void DiscordPlatformMessenger_ShouldImplementIPlatformMessenger()
    {
        Assert.True(typeof(IPlatformMessenger).IsAssignableFrom(typeof(DiscordPlatformMessenger)));
    }

    [Fact]
    public async Task AnswerInteractionAsync_ShouldStoreReplyForComponentModule()
    {
        var source = await ReadRepositoryFileAsync("src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs");

        Assert.Contains("DiscordInteractionReplyCache", source, StringComparison.Ordinal);
        Assert.Contains("interactionReplies.Store(reply)", source, StringComparison.Ordinal);
    }

    [Fact]
    public async Task DiscordPlatformMessenger_ShouldSupportSchedulerNotifications()
    {
        var source = await ReadRepositoryFileAsync("src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs");

        Assert.Contains("SendConfirmationRequestAsync", source, StringComparison.Ordinal);
        Assert.Contains("UpdateConfirmationRequestAsync", source, StringComparison.Ordinal);
        Assert.Contains("SendJoinLinkNotificationAsync", source, StringComparison.Ordinal);
        Assert.Contains("SendDirectSessionNotificationAsync", source, StringComparison.Ordinal);
        Assert.Contains("UpdateRescheduleVoteAsync", source, StringComparison.Ordinal);
        Assert.Contains("DiscordSessionBatchRenderer", source, StringComparison.Ordinal);
        Assert.Contains("DiscordRescheduleVotingRenderer", source, StringComparison.Ordinal);
        Assert.Contains("GetDMChannelAsync", source, StringComparison.Ordinal);
    }

    private static async Task<string> ReadRepositoryFileAsync(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 await File.ReadAllTextAsync(candidate);
            }

            directory = directory.Parent;
        }

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