package admin

import "strings"

func parseSortField(sort string) (field string, desc bool) {
	sort = strings.TrimSpace(sort)
	if sort == "" {
		return "", false
	}
	if strings.HasPrefix(sort, "-") {
		return strings.TrimPrefix(sort, "-"), true
	}
	return sort, false
}

func buildUserOrderBy(sort string) string {
	field, desc := parseSortField(sort)
	allowed := map[string]string{
		"created_at":  "created_at",
		"updated_at":  "updated_at",
		"email":       "LOWER(email)",
		"name":        "LOWER(name)",
		"status":      "status",
		"external_id": "LOWER(external_id)",
	}
	col, ok := allowed[field]
	if !ok {
		return "ORDER BY created_at DESC"
	}
	dir := "ASC"
	if desc {
		dir = "DESC"
	}
	return "ORDER BY " + col + " " + dir
}
