package com.cd.detection.db.core;

import com.cd.detection.db.repository.zoo.ZooRepository;
import com.cd.detection.domain.zoo.dto.ZooDto.AddRequest;
import com.cd.detection.domain.zoo.dto.ZooDto.AnimalRes;
import com.cd.detection.domain.zoo.dto.ZooDto.ModifyRequest;
import com.cd.detection.domain.zoo.dto.ZooDto.SearchListRequest;
import com.cd.detection.domain.zoo.dto.ZooDto.ZooWithAnimalsRes;
import com.cd.detection.entity.ZooEntity;
import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ZooCoreService {
  private final ZooRepository zooRepository;

  @Transactional
  public void saveZoo(AddRequest dto) {
    ZooEntity zooEntity = new ZooEntity();
    zooEntity.setZooName(dto.getZooName());
    zooEntity.setDescription(dto.getDescription());

    zooRepository.save(zooEntity);
  }

  @Transactional
  public void updateZoo(ModifyRequest dto) {
    ZooEntity zooEntity = zooRepository.findById(dto.getId()).orElseThrow(() -> new EntityNotFoundException("Zoo Id: " + dto.getId()));

    zooEntity.setZooName(dto.getZooName());
    zooEntity.setDescription(dto.getDescription());
    zooEntity.setUseYn(dto.getUseYn());
    zooRepository.save(zooEntity);
  }

  @Transactional
  public void deleteZoo(ModifyRequest dto) {
    ZooEntity zooEntity = zooRepository.findById(dto.getId()).orElseThrow(() -> new EntityNotFoundException("Zoo Id: " + dto.getId()));

    zooEntity.setDelYn(dto.getDelYn());
    zooRepository.save(zooEntity);
  }

  public Page<ZooWithAnimalsRes> getZooWithAnimals(SearchListRequest searchListRequest) {
    Page<ZooEntity> zoo = zooRepository.findAllWithAnimals(searchListRequest);

    return zoo.map(z -> {
      ZooWithAnimalsRes res = new ZooWithAnimalsRes();
      res.setZooId(z.getZooId());
      res.setZooName(z.getZooName());
      res.setDescription(z.getDescription());

      List<AnimalRes> animals = z.getAnimals().stream()
          .map(a -> {
            AnimalRes ar = new AnimalRes();
            ar.setAnimalId(a.getAnimalId());
            ar.setAnimalName(a.getAnimalName());
            ar.setSpecies(a.getSpecies());
            ar.setAge(a.getAge());
            return ar;
          })
          .toList();

      res.setAnimals(animals);
      return res;
    });
  }
}
