package premium_store.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import premium_store.model.Nation;
import premium_store.model.Tank;
import premium_store.repository.NationRepository;
import premium_store.service.exception.NationNotFoundException;
import premium_store.util.validation.ValidatorUtil;

import java.util.List;
import java.util.Optional;

@Service
public class NationService {
    private final NationRepository nationRepository;
    private final ValidatorUtil validatorUtil;

    public NationService(NationRepository nationRepository, ValidatorUtil validatorUtil){
        this.nationRepository = nationRepository;
        this.validatorUtil = validatorUtil;
    }

    @Transactional
    public Nation addNation(String nameNation){
        final Nation nation = new Nation(nameNation);
        validatorUtil.validate(nation);

        return nationRepository.save(nation);
    }

    //здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null
    @Transactional(readOnly = true)
    public Nation findNation(Long id){
        final Optional<Nation> nation =  nationRepository.findById(id);

        //благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения
        return nation.orElseThrow(() -> new NationNotFoundException(id));
    }

    @Transactional(readOnly = true)
    public List<Nation> findAllNations() {
        return nationRepository.findAll();
    }

    @Transactional
    public Nation updateNation(Long id, String newNation, Tank newTank) {
        if(id <= 0){
            throw new IllegalArgumentException(String.format("Incorrect id: [%s]", id));
        }

        final Nation currentNation = findNation(id);

        if (StringUtils.hasText(newNation)) {
            currentNation.setNation(newNation);
        }

        if(newTank != null){
            currentNation.setTanksOfThisNation(newTank);
        }

        return nationRepository.save(currentNation);
    }

    @Transactional
    public Nation deleteNation(Long id) {
        final Nation currentNation = findNation(id);
        nationRepository.delete(currentNation);

        return currentNation;
    }

    @Transactional
    public void deleteAllNations() {
        nationRepository.deleteAll();
    }
}
