package utils

import "strings"

// MaskEmail masks an email address for logging purposes.
// Example: "user@example.com" becomes "u***@e***.com"
// This preserves enough information for debugging while protecting privacy.
func MaskEmail(email string) string {
	if email == "" {
		return ""
	}

	parts := strings.Split(email, "@")
	if len(parts) != 2 {
		// Not a valid email format, mask most of it
		if len(email) <= 2 {
			return "***"
		}
		return string(email[0]) + "***"
	}

	localPart := parts[0]
	domainPart := parts[1]

	// Mask local part: show first character, mask the rest
	maskedLocal := maskPart(localPart)

	// Mask domain: show first character of domain name, mask rest, keep TLD
	maskedDomain := maskDomain(domainPart)

	return maskedLocal + "@" + maskedDomain
}

// maskPart masks a string showing only the first character
func maskPart(s string) string {
	if len(s) == 0 {
		return "***"
	}
	if len(s) == 1 {
		return s + "***"
	}
	return string(s[0]) + "***"
}

// maskDomain masks the domain part, preserving the TLD
func maskDomain(domain string) string {
	lastDot := strings.LastIndex(domain, ".")
	if lastDot == -1 {
		// No TLD found, just mask it
		return maskPart(domain)
	}

	domainName := domain[:lastDot]
	tld := domain[lastDot:] // includes the dot

	return maskPart(domainName) + tld
}
