package de.pnreichmuth.timekeep_backend.services; import de.pnreichmuth.timekeep_backend.entities.Station; import de.pnreichmuth.timekeep_backend.exceptions.StationExistsException; import de.pnreichmuth.timekeep_backend.repositories.StationRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service @Slf4j @RequiredArgsConstructor public class StationService { private final StationRepository stationRepository; private void checkIfStationIsDuplicate(Station station){ List stations = stationRepository.findAll(); if(stations.isEmpty()) return; if( stations.stream().anyMatch( dbStation -> dbStation.getName().equals(station.getName()) && dbStation.getLocation().equals(station.getLocation()) && !dbStation.getId().equals(station.getId()) ) ) throw new StationExistsException( "A station named %s already exists at the location %s".formatted(station.getName(), station.getLocation()), station ); } public Optional createStation(String name, String location){ Station station = new Station(name,location); checkIfStationIsDuplicate(station); stationRepository.save(station); return Optional.of(station); } }