package helpers

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

var (
	// keep letters, numbers, spaces, and hyphens
	slugRegex = regexp.MustCompile(`[^a-z0-9\s-]`)
	spaceRe   = regexp.MustCompile(`\s+`)
	dashRe    = regexp.MustCompile(`-+`)
)

// GenerateSlug creates a URL-safe slug from a given string (e.g. company name).
func GenerateSlug(name string) string {
	// lowercase
	slug := strings.ToLower(name)

	// normalize unicode accents (é -> e, ü -> u, etc.)
	slug = strings.Map(func(r rune) rune {
		if unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSpace(r) || r == '-' {
			return r
		}
		return -1
	}, slug)

	// remove unwanted chars
	slug = slugRegex.ReplaceAllString(slug, "")

	// replace spaces with dash
	slug = spaceRe.ReplaceAllString(slug, "-")

	// collapse multiple dashes
	slug = dashRe.ReplaceAllString(slug, "-")

	// trim leading/trailing dash
	slug = strings.Trim(slug, "-")

	return slug
}
