| 1 | package com.tecmilenio.mapsconect.service; |
| 2 | |
| 3 | import com.tecmilenio.mapsconect.dto.MateriaDTO; |
| 4 | import com.tecmilenio.mapsconect.entity.Materia; |
| 5 | import com.tecmilenio.mapsconect.exception.ResourceNotFoundException; |
| 6 | import com.tecmilenio.mapsconect.repository.MateriaRepository; |
| 7 | import org.springframework.beans.factory.annotation.Autowired; |
| 8 | import org.springframework.stereotype.Service; |
| 9 | |
| 10 | import java.util.List; |
| 11 | |
| 12 | @Service |
| 13 | public class MateriaService { |
| 14 | |
| 15 | @Autowired |
| 16 | private MateriaRepository materiaRepository; |
| 17 | |
| 18 | public List<MateriaDTO> listar(String tipo) { |
| 19 | List<Materia> materias; |
| 20 | if (tipo != null && !tipo.isBlank()) { |
| 21 | Materia.Tipo tipoEnum; |
| 22 | try { |
| 23 | tipoEnum = Materia.Tipo.valueOf(tipo.toUpperCase()); |
| 24 | } catch (IllegalArgumentException ex) { |
| 25 | throw new IllegalArgumentException("Tipo de materia inválido: " + tipo); |
| 26 | } |
| 27 | materias = materiaRepository.findByTipo(tipoEnum); |
| 28 | } else { |
| 29 | materias = materiaRepository.findAll(); |
| 30 | } |
| 31 | return materias.stream().map(this::mapearADTO).toList(); |
| 32 | } |
| 33 | |
| 34 | public MateriaDTO obtenerPorId(Integer id) { |
| 35 | Materia materia = materiaRepository.findById(id) |
| 36 | .orElseThrow(() -> new ResourceNotFoundException("Materia no encontrada")); |
| 37 | return mapearADTO(materia); |
| 38 | } |
| 39 | |
| 40 | private MateriaDTO mapearADTO(Materia materia) { |
| 41 | return MateriaDTO.builder() |
| 42 | .id(materia.getId()) |
| 43 | .clave(materia.getClave()) |
| 44 | .nombre(materia.getNombre()) |
| 45 | .creditos(materia.getCreditos()) |
| 46 | .tipo(materia.getTipo() != null ? materia.getTipo().name() : null) |
| 47 | .build(); |
| 48 | } |
| 49 | |
| 50 | } |