package kz.konturai.parser.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

final class SocialPostTextFormatter {

    static final String CONTACTS_BLOCK = "telegram - https://t.me/konturaibot\nномер для звонка - tel:+77273901485";

    private static final String ELLIPSIS = "...";
    private static final String BLOCK_SEPARATOR = "\n\n";

    private SocialPostTextFormatter() {
    }

    static String buildPostText(String postText, List<String> hashtags) {
        return buildPostText(postText, hashtags, 0);
    }

    static String buildPostText(String postText, List<String> hashtags, int maxLength) {
        String safePostText = postText != null ? postText : "";
        String hashtagsText = buildHashtagsText(hashtags);
        String fullText = joinBlocks(safePostText, CONTACTS_BLOCK, hashtagsText);

        if (maxLength <= 0 || fullText.length() <= maxLength) {
            return fullText;
        }

        return buildPostTextWithinLimit(safePostText, hashtagsText, maxLength);
    }

    private static String buildPostTextWithinLimit(String postText, String hashtagsText, int maxLength) {
        String requiredSuffix = joinBlocks(CONTACTS_BLOCK, hashtagsText);
        if (requiredSuffix.length() >= maxLength) {
            return requiredSuffix.substring(0, maxLength);
        }

        if (postText.isEmpty()) {
            return requiredSuffix;
        }

        int availablePostLength = maxLength - requiredSuffix.length() - BLOCK_SEPARATOR.length();
        if (availablePostLength <= 0) {
            return requiredSuffix;
        }

        return truncateWithEllipsis(postText, availablePostLength) + BLOCK_SEPARATOR + requiredSuffix;
    }

    private static String buildHashtagsText(List<String> hashtags) {
        if (hashtags == null || hashtags.isEmpty()) {
            return "";
        }

        return hashtags.stream()
                .filter(tag -> tag != null && !tag.isBlank())
                .map(String::strip)
                .map(tag -> tag.startsWith("#") ? tag : "#" + tag)
                .collect(Collectors.joining(" "));
    }

    private static String joinBlocks(String... blocks) {
        List<String> filledBlocks = new ArrayList<>();
        for (String block : blocks) {
            if (block != null && !block.isBlank()) {
                filledBlocks.add(block);
            }
        }
        return String.join(BLOCK_SEPARATOR, filledBlocks);
    }

    private static String truncateWithEllipsis(String value, int maxLength) {
        if (value.length() <= maxLength) {
            return value;
        }
        if (maxLength <= ELLIPSIS.length()) {
            return value.substring(0, maxLength);
        }
        return value.substring(0, maxLength - ELLIPSIS.length()) + ELLIPSIS;
    }
}
