package com.example.fercoganbackend.service; import com.example.fercoganbackend.entity.Puja; import com.example.fercoganbackend.entity.Remate; import com.example.fercoganbackend.repository.PujaRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.fercoganbackend.repository.UsuarioRepository; import com.example.fercoganbackend.repository.CabanaRepository; import com.example.fercoganbackend.repository.LoteRepository; import com.example.fercoganbackend.repository.RemateRepository; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Service public class PujaService { @Autowired private UsuarioRepository usuarioRepository; @Autowired private CabanaRepository cabanaRepository; @Autowired private LoteRepository loteRepository; @Autowired private RemateRepository remateRepository; @Autowired private PujaRepository pujaRepository; public List findAll() { return pujaRepository.findAll(); } public List findForRemtae(Long id){ return pujaRepository.findByLote_Remate_Id(id); } public List findForLoteAndRemate( Long loteId, Long remateId){ return pujaRepository.findByLote_IdAndLote_Remate_Id( loteId,remateId); } public Optional findForIdAndLoteAndRemate(Long Id, Long loteId, Long remateId){ return pujaRepository.findByIdAndLote_IdAndLote_Remate_Id( Id, loteId,remateId); } public List findForLoteAndRemateAndDate(Long loteId, Long remateId, LocalDateTime fecha){ return pujaRepository.findByLote_IdAndLote_Remate_IdAndFechaAfter(loteId, remateId, fecha); } public List fingForReporte(Long id){ return pujaRepository.findMayorPujaPorLotePorRemateNative(id); } public Optional findById(Long id) { return pujaRepository.findById(id); } public Puja save(Puja puja) { // Validar USUARIO if (puja.getUsuario() == null || puja.getUsuario().getId() == null) { throw new RuntimeException("El usuario es obligatorio"); } var usuario = usuarioRepository.findById(puja.getUsuario().getId()) .orElseThrow(() -> new RuntimeException("Usuario no encontrado")); // Validar CABAÑA if (puja.getCabana() == null || puja.getCabana().getId() == null) { throw new RuntimeException("La cabaña es obligatoria"); } var cabana = cabanaRepository.findById(puja.getCabana().getId()) .orElseThrow(() -> new RuntimeException("Cabaña no encontrada")); // Validar LOTE if (puja.getLote() == null || puja.getLote().getId() == null) { throw new RuntimeException("El lote es obligatorio"); } var lote = loteRepository.findById(puja.getLote().getId()) .orElseThrow(() -> new RuntimeException("Lote no encontrado")); // Asignar entidades reales para que JPA las maneje correctamente puja.setUsuario(usuario); puja.setCabana(cabana); puja.setLote(lote); return pujaRepository.save(puja); } public void delete(Long id) { pujaRepository.deleteById(id); } }