package com.kamco.cd.training.postgres;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.PathBuilder;
import org.springframework.data.domain.Pageable;

public class QuerydslOrderUtil {
  /**
   * Pageable의 Sort 정보를 QueryDSL OrderSpecifier 배열로 변환
   *
   * @param pageable Spring Pageable
   * @param entityClass 엔티티 클래스 (예: User.class)
   * @param alias Q 엔티티 alias (예: "user")
   */
  public static <T> OrderSpecifier<?>[] getOrderSpecifiers(
      Pageable pageable, Class<T> entityClass, String alias) {
    PathBuilder<T> entityPath = new PathBuilder<>(entityClass, alias);

    return pageable.getSort().stream()
        .map(
            sort -> {
              Order order = sort.isAscending() ? Order.ASC : Order.DESC;
              // PathBuilder.get()는 컬럼명(String)을 동적 Path로 반환
              return new OrderSpecifier<>(
                  order, entityPath.get(sort.getProperty(), Comparable.class));
            })
        .toArray(OrderSpecifier[]::new);
  }
}
