namespace GmRelay.Bot.Infrastructure.Telegram;

public sealed record TelegramTopicDestination(
    int? MessageThreadId,
    bool ShouldCreateForumTopic,
    bool TopicCreatedByBot);

public static class TelegramTopicRouting
{
    public const string MissingForumTopicRightsMessage =
        "Не удалось создать Telegram topic. Сделайте бота admin и включите право Manage Topics, затем повторите команду.";

    public static TelegramTopicDestination ResolveNewScheduleDestination(
        bool chatIsForum,
        int? incomingMessageThreadId)
    {
        if (!chatIsForum)
        {
            return new TelegramTopicDestination(null, ShouldCreateForumTopic: false, TopicCreatedByBot: false);
        }

        if (incomingMessageThreadId.HasValue)
        {
            return new TelegramTopicDestination(
                incomingMessageThreadId,
                ShouldCreateForumTopic: false,
                TopicCreatedByBot: false);
        }

        return new TelegramTopicDestination(null, ShouldCreateForumTopic: true, TopicCreatedByBot: true);
    }

    public static bool ShouldDeleteForumTopic(bool topicCreatedByBot, int remainingSessionsInTopic) =>
        topicCreatedByBot && remainingSessionsInTopic == 0;

    public static bool IsMissingForumTopicRightsError(string apiError) =>
        apiError.Contains("not enough rights", StringComparison.OrdinalIgnoreCase) ||
        apiError.Contains("CHAT_ADMIN_REQUIRED", StringComparison.OrdinalIgnoreCase) ||
        apiError.Contains("not an administrator", StringComparison.OrdinalIgnoreCase);
}
