package com.saas.shared.util;

import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;

public class SlugUtils {
    
    private static final Pattern NON_ALPHANUMERIC = Pattern.compile("[^a-zA-Z0-9]");
    private static final Pattern MULTIPLE_UNDERSCORES = Pattern.compile("_+");
    private static final Pattern EDGE_UNDERSCORES = Pattern.compile("(^_|_$)");
    
    public static String toSlug(String input) {
        if (input == null || input.trim().isEmpty()) {
            throw new IllegalArgumentException("Tenant name cannot be null or empty");
        }
        
        String normalized = Normalizer.normalize(input, Normalizer.Form.NFD);
        String alphanumericOnly = NON_ALPHANUMERIC.matcher(normalized).replaceAll("_");
        String singleUnderscores = MULTIPLE_UNDERSCORES.matcher(alphanumericOnly).replaceAll("_");
        String trimmed = EDGE_UNDERSCORES.matcher(singleUnderscores).replaceAll("");
        String slug = trimmed.toLowerCase(Locale.ENGLISH);
        
        if (slug.isEmpty()) {
            throw new IllegalArgumentException(
                "Tenant name '" + input + "' contains no valid characters. " +
                "Please use letters or numbers in the tenant name."
            );
        }
        
        return slug;
    }
    
    public static String toTenantDatabaseName(String tenantName, String prefix) {
        String slug = toSlug(tenantName);
        return prefix + slug;
    }
}
