package purchasing

import (
	"strings"

	"github.com/jackc/pgx/v5/pgtype"
)

// sort whitelist helpers shared by the ERP table lists (ListDebts today,
// more later). A sort key coming from the query string must never reach SQL
// as an identifier, so every sortable column is named here and the SQL side
// compares against exactly these strings.

// sortDirOrNil normalizes the requested direction; empty means the column's
// natural (ascending) order.
func sortDirOrNil(dir string) pgtype.Text {
	switch strings.ToLower(strings.TrimSpace(dir)) {
	case "desc":
		return pgtype.Text{String: "desc", Valid: true}
	case "asc":
		return pgtype.Text{String: "asc", Valid: true}
	default:
		return pgtype.Text{}
	}
}

// sortByOrNil keeps the requested column only when it is in the whitelist;
// anything else falls back to the SQL's default order.
func sortByOrNil(by string, allowed []string) pgtype.Text {
	clean := strings.ToLower(strings.TrimSpace(by))
	if clean == "" {
		return pgtype.Text{}
	}
	for _, a := range allowed {
		if clean == a {
			return pgtype.Text{String: clean, Valid: true}
		}
	}
	return pgtype.Text{}
}

// debtSortColumns lists the sortable columns of ListDebts. Keep in lockstep
// with the ORDER BY branches in db/query/purchasing.sql.
var debtSortColumns = []string{
	"po_number", "supplier_name", "order_date", "due_date",
	"total_amount", "paid_amount", "remaining_amount",
}

// poSortColumns lists the sortable columns of ListPurchaseOrders. Keep in lockstep
// with the ORDER BY branches in db/query/purchasing.sql.
var poSortColumns = []string{
	"po_number", "supplier_name", "order_date", "expected_date",
	"status", "total_amount",
}
