// TODO 미사용시작
package com.kamco.cd.training.postgres.repository.dataset;

import com.kamco.cd.training.dataset.dto.MapSheetDto;
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
import com.kamco.cd.training.postgres.entity.QMapSheetEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import java.util.Optional;
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 MapSheetRepositoryImpl implements MapSheetRepositoryCustom {

  private final JPAQueryFactory queryFactory;
  private final QMapSheetEntity mapSheet = QMapSheetEntity.mapSheetEntity;

  @Override
  public Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq) {
    Pageable pageable = searchReq.toPageable();
    BooleanBuilder builder = new BooleanBuilder();

    // 데이터셋 ID 필터
    if (searchReq.getDatasetId() != null) {
      builder.and(mapSheet.datasetId.eq(searchReq.getDatasetId()));
    }

    // 삭제되지 않은 것만
    builder.and(mapSheet.deleted.isFalse());

    // Entity 직접 조회 (Projections 사용 지양)
    List<MapSheetEntity> content =
        queryFactory
            .selectFrom(mapSheet)
            .where(builder)
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize())
            .orderBy(mapSheet.createdDttm.desc())
            .fetch();

    // Count 쿼리 별도 실행 (null safe handling)
    long total =
        Optional.ofNullable(
                queryFactory.select(mapSheet.count()).from(mapSheet).where(builder).fetchOne())
            .orElse(0L);

    return new PageImpl<>(content, pageable, total);
  }
}
// TODO 미사용 끝
