package com.cd.detection.db.core;

import com.cd.detection.db.repository.zoo.AnimalRepository;
import com.cd.detection.domain.zoo.dto.AnimalDto;
import com.cd.detection.domain.zoo.dto.AnimalDto.AddRequest;
import com.cd.detection.domain.zoo.dto.AnimalDto.ModifyRequest;
import com.cd.detection.domain.zoo.dto.AnimalDto.SearchListRequest;
import com.cd.detection.entity.AnimalEntity;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class AnimalCoreService {
  private final AnimalRepository animalRepository;

  @Transactional
  public void saveZoo(AddRequest dto) {
    ZooEntity zoo = new ZooEntity();
    zoo.setZooId(dto.getZooId());   // FK만 세팅

    AnimalEntity animalEntity = new AnimalEntity();
    animalEntity.setZoo(zoo);
    animalEntity.setAnimalName(dto.getAnimalName());
    animalEntity.setSpecies(dto.getSpecies());
    animalEntity.setAge(dto.getAge());

    animalRepository.save(animalEntity);
  }

  @Transactional
  public void updateZoo(ModifyRequest dto) {
    AnimalEntity animalEntity  = animalRepository.findById(dto.getAnimalId()).orElseThrow(() -> new EntityNotFoundException("Animal Id: " + dto.getAnimalId()));

    animalEntity.setAnimalName(dto.getAnimalName());
    animalEntity.setSpecies(dto.getSpecies());
    animalEntity.setUseYn(dto.getUseYn());
    animalRepository.save(animalEntity);
  }

  @Transactional
  public void deleteZoo(ModifyRequest dto) {
    AnimalEntity animalEntity  = animalRepository.findById(dto.getAnimalId()).orElseThrow(() -> new EntityNotFoundException("Animal Id: " + dto.getAnimalId()));

    animalEntity.setDelYn(dto.getDelYn());
    animalRepository.save(animalEntity);
  }

  public Page<AnimalDto.Basic> getAnimals(SearchListRequest searchListRequest) {
    Page<AnimalEntity> animals = animalRepository.findAllAnimals(searchListRequest);

    return animals.map(a -> {
      AnimalDto.Basic res = new AnimalDto.Basic();
      res.setAnimalId(a.getAnimalId());
      res.setAnimalName(a.getAnimalName());
      res.setSpecies(a.getSpecies());
      res.setAge(a.getAge() != null ? a.getAge().toString() : null);
      res.setDelYn(a.getDelYn());
      res.setUseYn(a.getUseYn());
      return res;
    });
  }
}
