package io.gmss.fiscad.implementations.rfu.parametre;

import io.gmss.fiscad.entities.rfu.parametre.BaremRfuBati;
import io.gmss.fiscad.exceptions.BadRequestException;
import io.gmss.fiscad.exceptions.NotFoundException;
import io.gmss.fiscad.interfaces.rfu.parametre.BaremRfuService;
import io.gmss.fiscad.repositories.rfu.parametre.BaremRfuRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
@Service
public class BaremRfuServiceImpl implements BaremRfuService {
    private final BaremRfuRepository baremRfuRepository;

    public BaremRfuServiceImpl(BaremRfuRepository baremRfuRepository) {
        this.baremRfuRepository = baremRfuRepository;
    }

    @Override
    public BaremRfuBati createBaremRfu(BaremRfuBati baremRfuBati) throws BadRequestException {
        if (baremRfuBati.getId() != null) {
            throw new BadRequestException("Impossible de créer un nouvel bareme rfu ayant un id non null.");
        }
        return baremRfuRepository.save(baremRfuBati);
    }

    @Override
    public BaremRfuBati updateBaremRfu(Long id, BaremRfuBati baremRfuBati) throws NotFoundException {
        if (baremRfuBati.getId() == null) {
            throw new BadRequestException("Impossible de mettre à jour une nouvel bareme rfu ayant un id null.");
        }
        if (!baremRfuRepository.existsById(baremRfuBati.getId())) {
            throw new NotFoundException("Impossible de trouver le bareme spécifiée dans notre base de données.");
        }
        return baremRfuRepository.save(baremRfuBati);
    }

    @Override
    public void deleteBaremRfu(Long id) throws NotFoundException {
        Optional<BaremRfuBati> baremRfuOptional = baremRfuRepository.findById(id);
        if (baremRfuOptional.isPresent()) {
            baremRfuRepository.deleteById(baremRfuOptional.get().getId());
        } else {
            throw new NotFoundException("Impossible de trouver le Bareme spécifié dans notre base de données.");
        }
    }

    @Override
    public Page<BaremRfuBati> getBaremRfuList(Pageable pageable) {
        return baremRfuRepository.findAll(pageable);
    }

    @Override
    public List<BaremRfuBati> getBaremRfuList() {
        return baremRfuRepository.findAll();
    }

    @Override
    public List<BaremRfuBati> getBaremRfuByType(Long idCategorieBatiment) {
        return baremRfuRepository.findAllByCategorieBatiment_Id(idCategorieBatiment);
    }

    @Override
    public Optional<BaremRfuBati> getBaremRfuById(Long id) {
        return baremRfuRepository.findById(id);
    }
}
