package utils

import (
	"regexp"
	"strings"
	"unicode"
)

// Slugify converts a string to a URL-friendly slug, replacing Turkish characters
// with ASCII equivalents and ensuring lowercase, hyphen-separated result.
func Slugify(s string) string {
	if s == "" {
		return ""
	}

	// Map Turkish characters to ASCII
	replacer := strings.NewReplacer(
		"ç", "c", "Ç", "c",
		"ğ", "g", "Ğ", "g",
		"ı", "i", "İ", "i",
		"ö", "o", "Ö", "o",
		"ş", "s", "Ş", "s",
		"ü", "u", "Ü", "u",
		"’", "", "'", "",
	)
	s = replacer.Replace(s)

	// Normalize: keep letters, numbers, and spaces
	var b strings.Builder
	for _, r := range strings.TrimSpace(s) {
		if unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSpace(r) {
			b.WriteRune(r)
		} else {
			// convert other punctuation to space
			b.WriteRune(' ')
		}
	}

	out := strings.ToLower(b.String())

	// replace spaces with hyphens and collapse multiple hyphens
	out = strings.TrimSpace(out)
	// replace any sequence of non-alnum with hyphen
	re := regexp.MustCompile(`[^a-z0-9]+`)
	out = re.ReplaceAllString(out, "-")
	out = strings.Trim(out, "-")
	return out
}
