package service

import "strings"

type sortRule struct {
	keys []string
	asc  string
	desc string
}

func sortField(column string, keys ...string) sortRule {
	if len(keys) == 0 {
		keys = []string{column}
	}
	return sortRule{
		keys: keys,
		asc:  column + " ASC",
		desc: column + " DESC",
	}
}

func sortExpr(asc, desc string, keys ...string) sortRule {
	return sortRule{
		keys: keys,
		asc:  asc,
		desc: desc,
	}
}

func normalizeSortByRules(sort string, rules ...sortRule) string {
	for _, rule := range rules {
		for _, key := range rule.keys {
			key = strings.TrimSpace(key)
			if key == "" {
				continue
			}
			if sort == key {
				return rule.asc
			}
			if sort == "-"+key {
				return rule.desc
			}
		}
	}
	return ""
}

func joinSortClauses(clauses []string) string {
	return strings.Join(clauses, ", ")
}
