package sortkey

import "fmt"

// ActivePositiveSortClauses builds ORDER BY clauses where non-negative sort keys
// are treated as prioritized values. NULL/negative are grouped as empty values.
func ActivePositiveSortClauses(tableAlias, activeColumn, sortKeyColumn, fallbackColumn string, descending bool) []string {
	active := qualify(tableAlias, activeColumn)
	sortKey := qualify(tableAlias, sortKeyColumn)
	fallback := qualify(tableAlias, fallbackColumn)

	valid := fmt.Sprintf("%s = 1 AND %s IS NOT NULL AND %s >= 0", active, sortKey, sortKey)

	direction := "ASC"
	if descending {
		direction = "DESC"
	}

	return []string{
		fmt.Sprintf("%s DESC", active),
		fmt.Sprintf("CASE WHEN %s THEN 0 ELSE 1 END ASC", valid),
		fmt.Sprintf("CASE WHEN %s THEN %s END %s", valid, sortKey, direction),
		fmt.Sprintf("%s ASC", fallback),
	}
}

func qualify(tableAlias, column string) string {
	if tableAlias == "" {
		return column
	}
	return tableAlias + "." + column
}
