# xll_kit/services/mixins/order_by_mixin.py

class OrderByMixin:
    def apply_sort(self, query, sort: str):
        sort_keys = self._parse_sort_param(sort)
        clauses = self.crud.build_order_clauses(sort_keys)
        if clauses:
            query = query.order_by(*clauses)
        return query

    def _parse_sort_param(self, sort: str):
        """
        解析 sort 参数，返回排序字段列表
        前端传 ?sort=-created_at,title
        解析结果 [('created_at', True), ('title', False)]
        """
        sort_items = [s.strip() for s in sort.split(",") if s.strip()]
        result = []
        for item in sort_items:
            is_desc = item.startswith("-")
            field = item.lstrip("-")
            result.append((field, is_desc))
        return result
