package com.devjob.repository;

import com.devjob.domain.Company;
import com.devjob.domain.Job;
import jakarta.persistence.criteria.Join;
import org.springframework.data.jpa.domain.Specification;

/**
 * EP14: 검색 조건이 없으면 조건을 생략하고, 있으면 추가하는 동적 쿼리 조립.
 * Specification이 null을 반환하면 해당 조건은 자동으로 건너뛴다.
 *
 * 사용 예: jobRepository.findAll(
 *     JobSpecification.withKeyword(keyword).and(JobSpecification.withLocation(location)),
 *     pageable);
 */
public class JobSpecification {

    private JobSpecification() {
    }

    public static Specification<Job> withKeyword(String keyword) {
        return (root, query, cb) -> {
            if (keyword == null || keyword.isBlank()) {
                return null;
            }
            Join<Job, Company> company = root.join("company");
            return cb.or(
                    cb.like(cb.lower(root.get("title")), "%" + keyword.toLowerCase() + "%"),
                    cb.like(cb.lower(company.get("name")), "%" + keyword.toLowerCase() + "%")
            );
        };
    }

    public static Specification<Job> withLocation(String location) {
        return (root, query, cb) -> {
            if (location == null || location.isBlank()) {
                return null;
            }
            return cb.equal(root.join("company").get("location"), location);
        };
    }
}
