package com.cd.detection.db.repository.zoo;

import com.cd.detection.domain.zoo.dto.AnimalDto.SearchListRequest;
import com.cd.detection.entity.AnimalEntity;
import com.cd.detection.entity.QAnimalEntity;
import com.cd.detection.entity.QZooEntity;
import com.cd.detection.entity.ZooEntity;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
public class AnimalRepositoryImpl implements AnimalRepositoryCustom {
  private final JPAQueryFactory queryFactory;

  public AnimalRepositoryImpl(JPAQueryFactory queryFactory) {
    this.queryFactory = queryFactory;
  }

  @Override
  public Page<AnimalEntity> findAllAnimals(SearchListRequest searchListRequest) {
    Pageable pageable = searchListRequest.toPageable();
    QAnimalEntity animal = QAnimalEntity.animalEntity;

    // content 조회
    List<AnimalEntity> content = queryFactory
        .selectFrom(animal)
        .where(animal.delYn.eq(false))
        .distinct()
        .offset(pageable.getOffset())
        .limit(pageable.getPageSize())
        .fetch();

    // count 조회 (fetchJoin 제거)
    Long total = queryFactory
        .select(animal.count())
        .from(animal)
        .where(animal.delYn.eq(false))
        .fetchOne();

    return new PageImpl<>(content, pageable, total == null ? 0L : total);
  }
}
