using System.Text;

namespace AiLogia.Bot.Utils;

public static class TelegramMessageHelper
{
    public static IEnumerable<string> SplitMessageIntoChunks(string message, int maxLength = 4000)
    {
        var lines = message.Split('\n');
        var chunk = new StringBuilder();

        foreach (var line in lines)
        {
            if (chunk.Length + line.Length + 1 > maxLength)
            {
                yield return chunk.ToString();
                chunk.Clear();
            }

            chunk.AppendLine(line);
        }

        if (chunk.Length > 0)
            yield return chunk.ToString();
    }

    public static IEnumerable<string> FormatResultsMessageFromModel(Models.TestResultModel resultsModel)
    {
        if (!string.IsNullOrEmpty(resultsModel.Interpretation))
        {
            resultsModel.Interpretation = resultsModel.Interpretation.Replace("\\n", Environment.NewLine);
        }

        if (!string.IsNullOrEmpty(resultsModel.ResultText))
        {
            resultsModel.ResultText = resultsModel.ResultText.Replace("\\n", Environment.NewLine);
        }

        var sb = new StringBuilder();

        sb.AppendLine($"🧪 {resultsModel.TestTitle}");
        sb.AppendLine("🎉 Поздравляем, тест завершен!");
        sb.AppendLine();
        sb.AppendLine("🔍 *Результат:*");
        sb.AppendLine();
        sb.AppendLine($"*{resultsModel.ResultText}*");

        if (!string.IsNullOrWhiteSpace(resultsModel.Interpretation))
        {
            sb.AppendLine();
            sb.AppendLine(resultsModel.Interpretation);
        }

        sb.AppendLine();

        sb.AppendLine(TelegramTextEscaper.Escape($"@{resultsModel.BotUsername}"));

        return SplitMessageIntoChunks(sb.ToString());
    }
}
