package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.model.ImpactReseau;
import org.mte.numecoeval.referentiel.domain.model.id.ImpactReseauId;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity;
import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository;
import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper;
import org.springframework.stereotype.Service;

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


@Service
@Slf4j
@AllArgsConstructor
public class ImpactReseauJpaAdapter implements ReferentielPersistencePort<ImpactReseau, ImpactReseauId> {
    ImpactReseauRepository reseauRepository;

    ImpactReseauMapper reseauMapper;

    @Override
    public ImpactReseau save(ImpactReseau facteurImpact) throws ReferentielException {
        ImpactReseauEntity impactReseauEntity = reseauMapper.toEntity(facteurImpact);
        ImpactReseauEntity save = reseauRepository.save(impactReseauEntity);
        return reseauMapper.toDomain(save);
    }

    @Override
    public void saveAll(Collection<ImpactReseau> facteursImpacts) throws ReferentielException {
        List<ImpactReseauEntity> impactReseauEntities = reseauMapper.toEntity(facteursImpacts);
        reseauRepository.saveAll(impactReseauEntities);
    }


    @Override
    public ImpactReseau get(ImpactReseauId id) throws ReferentielException {
        ImpactReseauIdEntity reseauId = reseauMapper.toEntityId(id);
        Optional<ImpactReseauEntity> reseauEntityOptional = reseauRepository.findById(reseauId);
        return reseauMapper.toDomain(
                reseauEntityOptional.orElseThrow(() -> new ReferentielException("Impact Réseau non trouvé"))
        );
    }

    @Override
    public void purge() {
        reseauRepository.deleteAll();
    }

    @Override
    public List<ImpactReseau> getAll() {
        return ListUtils.emptyIfNull(reseauMapper.toDomains(reseauRepository.findAll()));
    }

}
