namespace GmRelay.Bot.Tests.Infrastructure.Telegram;

public sealed class TelegramTopicIntegrationSmokeTests
{
    [Fact]
    public async Task BotAndWebCode_ShouldPersistAndUseTopicOwnership()
    {
        var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V015__add_topic_ownership.sql");
        var createHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs");
        var deleteHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/ListSessions/DeleteSessionHandler.cs");
        var topicRouting = await ReadRepositoryFileAsync("src/GmRelay.Bot/Infrastructure/Telegram/TelegramTopicRouting.cs");

        Assert.Contains("topic_created_by_bot", migration, StringComparison.Ordinal);

        // The wizard-driven CreateSessionHandler threads the existing forum topic
        // (if any) into the draft; the shared creation command inherits it. Topic
        // auto-creation and rights handling live in TelegramTopicRouting.
        Assert.Contains("MessageThreadId", createHandler, StringComparison.Ordinal);
        Assert.Contains("ExternalThreadId", createHandler, StringComparison.Ordinal);
        Assert.Contains("ResolveNewScheduleDestination", topicRouting, StringComparison.Ordinal);
        Assert.Contains("MissingForumTopicRightsMessage", topicRouting, StringComparison.Ordinal);

        Assert.Contains("TopicCreatedByBot", deleteHandler, StringComparison.Ordinal);
        Assert.Contains("ShouldDeleteForumTopic", deleteHandler, StringComparison.Ordinal);
        Assert.Contains("RemainingInTopic", deleteHandler, StringComparison.Ordinal);
    }

    [Fact]
    public async Task GroupNotifications_ShouldSendToStoredForumTopic()
    {
        var confirmationHandler = await ReadRepositoryFileAsync("src/GmRelay.Shared/Features/Confirmation/SendConfirmation/SendConfirmationHandler.cs");
        var joinLinkHandler = await ReadRepositoryFileAsync("src/GmRelay.Shared/Features/Reminders/SendJoinLink/SendJoinLinkHandler.cs");
        var rsvpHandler = await ReadRepositoryFileAsync("src/GmRelay.Shared/Features/Confirmation/HandleRsvp/HandleRsvpHandler.cs");
        var cancelHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/CancelSessionHandler.cs");
        var initiateRescheduleHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/RescheduleSession/InitiateRescheduleHandler.cs");
        var rescheduleInputHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleTimeInputHandler.cs");
        var sharedRescheduleInputHandler = await ReadRepositoryFileAsync("src/GmRelay.Shared/Features/Sessions/RescheduleSession/HandleRescheduleTimeInputHandler.cs");
        var rescheduleDeadlineService = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/RescheduleSession/RescheduleVotingDeadlineService.cs");
        var telegramMessenger = await ReadRepositoryFileAsync("src/GmRelay.Bot/Infrastructure/Telegram/TelegramPlatformMessenger.cs");

        Assert.Contains("int? ThreadId", confirmationHandler, StringComparison.Ordinal);
        Assert.Contains("s.thread_id AS ThreadId", confirmationHandler, StringComparison.Ordinal);
        Assert.Contains("ExternalThreadId", confirmationHandler, StringComparison.Ordinal);

        Assert.Contains("int? ThreadId", joinLinkHandler, StringComparison.Ordinal);
        Assert.Contains("s.thread_id AS ThreadId", joinLinkHandler, StringComparison.Ordinal);
        Assert.Contains("ExternalThreadId", joinLinkHandler, StringComparison.Ordinal);

        Assert.Contains("PlatformMessageRef ConfirmationMessage", rsvpHandler, StringComparison.Ordinal);
        Assert.Contains("UpdateConfirmationRequestAsync", rsvpHandler, StringComparison.Ordinal);

        Assert.Contains("int? MessageThreadId", cancelHandler, StringComparison.Ordinal);
        Assert.Contains("TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId)", cancelHandler, StringComparison.Ordinal);

        Assert.Contains("int? MessageThreadId", initiateRescheduleHandler, StringComparison.Ordinal);
        Assert.Contains("TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId)", initiateRescheduleHandler, StringComparison.Ordinal);

        Assert.Contains("message.MessageThreadId", rescheduleInputHandler, StringComparison.Ordinal);
        Assert.Contains("s.thread_id AS ThreadId", sharedRescheduleInputHandler, StringComparison.Ordinal);
        Assert.Contains("TelegramPlatformIds.Group(message.Chat.Id, message.MessageThreadId", rescheduleInputHandler, StringComparison.Ordinal);

        Assert.Contains("int? ThreadId", rescheduleDeadlineService, StringComparison.Ordinal);
        Assert.Contains("s.thread_id AS ThreadId", rescheduleDeadlineService, StringComparison.Ordinal);
        Assert.Contains("TelegramPlatformIds.Group(telegramFields.TelegramChatId, telegramFields.ThreadId)", rescheduleDeadlineService, StringComparison.Ordinal);

        Assert.Contains("messageThreadId", telegramMessenger, StringComparison.Ordinal);
        Assert.Contains("ExternalThreadId", telegramMessenger, StringComparison.Ordinal);
    }

    [Fact]
    public async Task WebTemplateBatches_ShouldCreateAndPersistForumTopic()
    {
        var sessionService = await ReadRepositoryFileAsync("src/GmRelay.Web/Services/SessionService.cs");

        Assert.Contains("GetChat", sessionService, StringComparison.Ordinal);
        Assert.Contains("CreateForumTopic", sessionService, StringComparison.Ordinal);
        Assert.Contains("thread_id, topic_created_by_bot", sessionService, StringComparison.Ordinal);
        Assert.Contains("ThreadId = messageThreadId", sessionService, StringComparison.Ordinal);
        Assert.Contains("TopicCreatedByBot = topicCreatedByBot", sessionService, StringComparison.Ordinal);
        Assert.Contains("messageThreadId: messageThreadId", sessionService, 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}'.");
    }
}
