package com.kamco.cd.training.postgres.repository.model;

import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;

import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
@RequiredArgsConstructor
public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {

  private final JPAQueryFactory queryFactory;

  /**
   * 모델 목록 조회
   *
   * @param req
   * @return
   */
  @Override
  public Page<ModelMasterEntity> findByModels(ModelTrainMngDto.SearchReq req) {
    Pageable pageable = req.toPageable();
    BooleanBuilder builder = new BooleanBuilder();

    if (req.getStatus() != null && !req.getStatus().isEmpty()) {
      builder.and(modelMasterEntity.statusCd.eq(req.getStatus()));
    }

    if (req.getModelNo() != null && !req.getModelNo().isEmpty()) {
      builder.and(modelMasterEntity.modelNo.eq(req.getModelNo()));
    }

    List<ModelMasterEntity> content =
        queryFactory
            .selectFrom(modelMasterEntity)
            .where(builder)
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize())
            .orderBy(modelMasterEntity.createdDttm.desc())
            .fetch();

    // Count 쿼리 별도 실행 (null safe handling)
    Long total =
        queryFactory
            .select(modelMasterEntity.count())
            .from(modelMasterEntity)
            .where(builder)
            .fetchOne();

    long totalCount = (total != null) ? total : 0L;

    return new PageImpl<>(content, pageable, totalCount);
  }

  /**
   * 모델 조회
   *
   * @param uuid
   * @return
   */
  @Override
  public Optional<ModelMasterEntity> findByUuid(UUID uuid) {
    return Optional.ofNullable(
        queryFactory
            .select(modelMasterEntity)
            .from(modelMasterEntity)
            .where(modelMasterEntity.uuid.eq(uuid))
            .fetchOne());
  }

  @Override
  public Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn) {
    return Optional.empty();
  }
}
