package com.oguerreiro.resilient.service.query;

import java.util.List;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oguerreiro.resilient.domain.Unit;
import com.oguerreiro.resilient.domain.Unit_;
import com.oguerreiro.resilient.repository.UnitRepository;
import com.oguerreiro.resilient.service.criteria.UnitConverterCriteria;
import com.oguerreiro.resilient.service.criteria.UnitCriteria;
import com.oguerreiro.resilient.service.dto.UnitDTO;
import com.oguerreiro.resilient.service.mapper.UnitMapper;

import jakarta.persistence.criteria.JoinType;

/**
 * Service for executing complex queries for {@link Unit} entities in the
 * database. The main input is a {@link UnitCriteria} which gets converted
 * to {@link Specification}, in a way that all the filters must apply. It
 * returns a {@link List} of {@link UnitDTO} which fulfills the criteria.
 */
@Service
@Transactional(readOnly = true)
public class UnitQueryService extends AbstractQueryService<Unit, UnitDTO, Long, UnitCriteria> {

  public UnitQueryService(UnitRepository unitRepository, UnitMapper unitMapper) {
    super(unitRepository, unitMapper);
  }

  /**
   * Function to convert {@link UnitConverterCriteria} to a {@link Specification}
   * 
   * @param  criteria The object which holds all the filters, which the entities
   *                  should match.
   * @return          the matching {@link Specification} of the entity.
   */
  protected Specification<Unit> createSpecification(UnitCriteria criteria) {
    Specification<Unit> specification = Specification.where(null);
    if (criteria != null) {
      // This has to be called first, because the distinct method returns null
      if (criteria.getDistinct() != null) {
        specification = specification.and(distinct(criteria.getDistinct()));
      }
      if (criteria.getId() != null) {
        specification = specification.and(buildRangeSpecification(criteria.getId(), Unit_.id));
      }
      if (criteria.getCode() != null) {
        specification = specification.and(buildStringSpecification(criteria.getCode(), Unit_.code));
      }
      if (criteria.getName() != null) {
        specification = specification.and(buildStringSpecification(criteria.getName(), Unit_.name));
      }
      if (criteria.getSymbol() != null) {
        specification = specification.and(buildStringSpecification(criteria.getSymbol(), Unit_.symbol));
      }
      if (criteria.getDescription() != null) {
        specification = specification.and(buildStringSpecification(criteria.getDescription(), Unit_.description));
      }
      if (criteria.getUnitTypeId() != null) {
        specification = specification.and(buildSpecification(criteria.getUnitTypeId(),
            root -> root.join(Unit_.unitType, JoinType.LEFT).get(ID_ATTRIBUTE_NAME)));
      }

    }
    return specification;
  }
}
