package com.gcsc.connection.monitoring.spec;

import com.gcsc.connection.monitoring.dto.RequestLogSearchDto;
import com.gcsc.connection.monitoring.entity.SnpApiRequestLog;
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

public class RequestLogSpecification {

    private RequestLogSpecification() {
    }

    /**
     * 검색 조건 기반 Specification 생성
     */
    public static Specification<SnpApiRequestLog> withFilters(RequestLogSearchDto dto) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (dto.startDate() != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("requestedAt"), dto.startDate()));
            }
            if (dto.endDate() != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("requestedAt"), dto.endDate()));
            }
            if (dto.serviceId() != null) {
                predicates.add(cb.equal(root.get("service").get("serviceId"), dto.serviceId()));
            }
            if (dto.requestStatus() != null && !dto.requestStatus().isBlank()) {
                predicates.add(cb.equal(root.get("requestStatus"), dto.requestStatus()));
            }
            if (dto.requestMethod() != null && !dto.requestMethod().isBlank()) {
                predicates.add(cb.equal(root.get("requestMethod"), dto.requestMethod()));
            }
            if (dto.requestIp() != null && !dto.requestIp().isBlank()) {
                predicates.add(cb.like(root.get("requestIp"), dto.requestIp() + "%"));
            }

            query.orderBy(cb.desc(root.get("requestedAt")));
            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}
