package org.cmh.backend.CourseManagement.specification;

import org.cmh.backend.CourseManagement.model.Course;
import org.springframework.data.jpa.domain.Specification;

import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

public class CourseSpecification {

    public static Specification<Course> searchCourses(
            String title, String author, String description, String sortOrder) {

        return (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (title != null && !title.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("title"), "%" + title + "%"));
            }
            if (author != null && !author.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("author"), "%" + author + "%"));
            }
            if (description != null && !description.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("description"), "%" + description + "%"));
            }
            if (sortOrder != null && !sortOrder.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("orderNo"), "%" + sortOrder+ "%"));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
    }
    public static Specification<Course> sortCourses(String sortField, String sortDirection) {
        return (root, query, cb) -> {
            if ("asc".equalsIgnoreCase(sortDirection)) {
                query.orderBy(cb.asc(root.get(sortField)));
            } else if ("desc".equalsIgnoreCase(sortDirection)) {
                query.orderBy(cb.desc(root.get(sortField)));
            }
            return cb.conjunction();
        };
    }
}