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

import com.cd.detection.domain.zoo.dto.ZooDto.SearchListRequest;
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.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
public class ZooRepositoryImpl implements ZooRepositoryCustom {

  private final JPAQueryFactory queryFactory;

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

  @Override
  public PageImpl<ZooEntity> findAllWithAnimals(SearchListRequest searchListRequest) {
    Pageable pageable = searchListRequest.toPageable();
    QZooEntity zoo = QZooEntity.zooEntity;

    // content 조회
    List<ZooEntity> content = queryFactory
        .selectFrom(zoo)
        .leftJoin(zoo.animals).fetchJoin()
        .where(zoo.delYn.eq(false))
        .distinct()
        .offset(pageable.getOffset())
        .limit(pageable.getPageSize())
        .fetch();

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

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