package shared

import (
	"strings"

	"github.com/gin-gonic/gin"
)

func UserIdentityFilterFromQuery(c *gin.Context, prefix string) UserIdentityFilter {
	prefix = strings.TrimSpace(prefix)
	return UserIdentityFilter{
		UserID:        firstQuery(c, queryNames(prefix, "user_id", "userId")...),
		DisplayUserID: firstQuery(c, queryNames(prefix, "display_user_id", "displayUserId")...),
		Username:      firstQuery(c, queryNames(prefix, "username", "username")...),
	}
}

func firstQuery(c *gin.Context, names ...string) string {
	for _, name := range names {
		if value := strings.TrimSpace(c.Query(name)); value != "" {
			return value
		}
	}
	return ""
}

func queryNames(prefix string, snake string, camel string) []string {
	if prefix == "" {
		return []string{snake, camel}
	}
	return []string{prefix + "_" + snake, prefix + upperFirst(camel)}
}

func upperFirst(value string) string {
	if value == "" {
		return ""
	}
	return strings.ToUpper(value[:1]) + value[1:]
}
