package com.pandoli365.bibimbap.jam;

import java.util.regex.Pattern;

public final class JamSlugs {

    private static final int MAX_BASE_LENGTH = 72;
    private static final int MAX_SLUG_LENGTH = 80;
    private static final String FALLBACK = "jam";

    private static final Pattern DISALLOWED = Pattern.compile("[^\\p{IsHangul}a-z0-9]+");
    private static final Pattern MULTI_HYPHEN = Pattern.compile("-{2,}");
    private static final Pattern TRIM_HYPHEN = Pattern.compile("^-+|-+$");

    private JamSlugs() {
    }

    public static String generate(String title) {
        String base = title == null ? "" : title;
        String lowered = base.toLowerCase();
        String hyphenated = DISALLOWED.matcher(lowered).replaceAll("-");
        String collapsed = MULTI_HYPHEN.matcher(hyphenated).replaceAll("-");
        String trimmed = TRIM_HYPHEN.matcher(collapsed).replaceAll("");

        String truncated = trimmed;
        if (truncated.length() > MAX_BASE_LENGTH) {
            truncated = truncated.substring(0, MAX_BASE_LENGTH);
            truncated = TRIM_HYPHEN.matcher(truncated).replaceAll("");
        }

        return truncated.isEmpty() ? FALLBACK : truncated;
    }

    public static String withSuffix(String baseSlug, int n) {
        String suffix = "-" + n;
        int allowedBase = MAX_SLUG_LENGTH - suffix.length();
        String trimmedBase = baseSlug;
        if (trimmedBase.length() > allowedBase) {
            trimmedBase = trimmedBase.substring(0, allowedBase);
            trimmedBase = TRIM_HYPHEN.matcher(trimmedBase).replaceAll("");
        }
        return trimmedBase + suffix;
    }
}
