package com.kamco.cd.kamcoback.Innopam.postgres.repository;

import static com.kamco.cd.kamcoback.Innopam.postgres.entity.QDetectMastEntity.detectMastEntity;

import com.kamco.cd.kamcoback.Innopam.dto.DetectMastDto.DetectMastSearch;
import com.kamco.cd.kamcoback.Innopam.postgres.entity.DetectMastEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class DetectMastRepositoryImpl implements DetectMastRepositoryCustom {

  private final JPAQueryFactory queryFactory;

  @Override
  public List<DetectMastEntity> findDetectMastList(DetectMastSearch detectMast) {

    BooleanBuilder whereBuilder = new BooleanBuilder();

    if (StringUtils.isNotBlank(detectMast.getCprsAdYr())) {
      whereBuilder.and(detectMastEntity.cprsAdYr.eq(detectMast.getCprsAdYr()));
    }

    if (StringUtils.isNotBlank(detectMast.getCprsBfYr())) {
      whereBuilder.and(detectMastEntity.cprsBfYr.eq(detectMast.getCprsBfYr()));
    }

    if (detectMast.getDtctSno() != null) {
      whereBuilder.and(detectMastEntity.dtctSno.eq(detectMast.getDtctSno()));
    }

    return queryFactory.select(detectMastEntity).from(detectMastEntity).where(whereBuilder).fetch();
  }

  @Override
  public DetectMastEntity findPnuData(DetectMastSearch detectMast) {

    BooleanBuilder whereBuilder = new BooleanBuilder();

    whereBuilder.and(detectMastEntity.cprsAdYr.eq(detectMast.getCprsAdYr()));
    whereBuilder.and(detectMastEntity.cprsBfYr.eq(detectMast.getCprsBfYr()));
    whereBuilder.and(detectMastEntity.dtctSno.eq(detectMast.getDtctSno()));

    if (detectMast.getFeatureId() != null) {
      whereBuilder.and(detectMastEntity.featureId.eq(detectMast.getFeatureId()));
    }

    return queryFactory
        .select(detectMastEntity)
        .from(detectMastEntity)
        .where(whereBuilder)
        .fetchOne();
  }
}
