package br.gov.sigefp.rh.specification;

import br.gov.sigefp.rh.domain.Agent;
import org.springframework.data.jpa.domain.Specification;

import java.util.UUID;

/**
 * Specifications para filtrar agentes de forma dinâmica.
 */
public class AgentSpecifications {

    public static Specification<Agent> hasStatus(String status) {
        return (root, query, cb) -> status == null ? null : cb.equal(root.get("status"), status);
    }

    public static Specification<Agent> hasOrgUnit(UUID orgUnitId) {
        return (root, query, cb) -> {
            if (orgUnitId == null)
                return null;
            System.out.println("DEBUG SPEC: Filtering by orgUnit ID: " + orgUnitId);
            return cb.equal(root.get("orgUnit"), orgUnitId);
        };
    }

    public static Specification<Agent> hasOrgUnitIn(java.util.List<UUID> orgUnitIds) {
        return (root, query, cb) -> {
            if (orgUnitIds == null || orgUnitIds.isEmpty())
                return null;
            System.out.println("DEBUG SPEC: Filtering by orgUnit LIST: " + orgUnitIds.size() + " units");
            return root.get("orgUnit").in(orgUnitIds);
        };
    }

    public static Specification<Agent> hasPosition(UUID positionId) {
        return (root, query, cb) -> positionId == null ? null : cb.equal(root.get("position"), positionId);
    }

    public static Specification<Agent> hasFunctionalSituation(String functionalSituation) {
        return (root, query, cb) -> functionalSituation == null ? null
                : cb.equal(root.get("functionalSituation"), functionalSituation);
    }

    public static Specification<Agent> hasAppointmentType(String appointmentType) {
        return (root, query, cb) -> appointmentType == null ? null
                : cb.equal(root.get("appointmentType"), appointmentType);
    }

    public static Specification<Agent> searchByQuery(String query) {
        return (root, criteriaQuery, cb) -> {
            if (query == null || query.trim().isEmpty()) {
                return null;
            }
            String searchPattern = "%" + query.toLowerCase() + "%";
            return cb.or(
                    cb.like(cb.lower(root.get("fullName")), searchPattern),
                    cb.like(cb.lower(root.get("matricula")), searchPattern),
                    cb.like(cb.lower(root.get("nif")), searchPattern),
                    cb.like(cb.lower(root.get("biNumber")), searchPattern));
        };
    }
}
