package de.votian.services.service;

import de.votian.services.entity.Address;
import de.votian.services.repository.AddressRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Optional;

@Service
@Transactional
public class AddressService {

    private final AddressRepository addressRepository;

    public AddressService(AddressRepository addressRepository) {
        this.addressRepository = addressRepository;
    }

    public Optional<Address> findById(Long id) {
        return addressRepository.findById(Objects.requireNonNull(id));
    }

    public Address findOrCreate(String street, String zipcode, String city, String country) {
        return addressRepository.findByStreetAndZipcodeAndCityAndCountry(street, zipcode, city, country)
                .orElseGet(() -> {
                    Address addr = new Address();
                    addr.setStreet(street);
                    addr.setZipcode(zipcode);
                    addr.setCity(city);
                    addr.setCountry(country);
                    return addressRepository.save(addr);
                });
    }

    public Address save(Address address) {
        return addressRepository.save(Objects.requireNonNull(address));
    }
}
