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.ImpactMessagerie;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.CritereRepository;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactMessagerieRepository;
import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactMessagerieMapper;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
@AllArgsConstructor
public class ImpactMessagerieJpaAdapter implements ReferentielPersistencePort<ImpactMessagerie,String> {

    ImpactMessagerieMapper impactMessagerieMapper;
    ImpactMessagerieRepository impactMessagerieRepository;
    CritereRepository critereRepository;

    @Override
    public ImpactMessagerie save(ImpactMessagerie referentiel) throws ReferentielException {
        var entity = impactMessagerieRepository.save(impactMessagerieMapper.toEntity(referentiel));
        return impactMessagerieMapper.toDomain(entity);
    }

    @Override
    public void saveAll(Collection<ImpactMessagerie> domains) throws ReferentielException {
        impactMessagerieRepository.saveAll(impactMessagerieMapper.toEntities(domains));
    }

    @Override
    public ImpactMessagerie get(String critere) throws ReferentielException {
        if(critere != null) {
            var entityOpt=  impactMessagerieRepository.findById(critere);
            return entityOpt
                    .map(impactMessagerieEntity -> impactMessagerieMapper.toDomain(impactMessagerieEntity))
                    .orElseThrow(() -> new ReferentielException("ImpactMessagerie non trouvé"));
        }
        throw new ReferentielException("ImpactMessagerie non trouvé");
    }

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

    @Override
    public List<ImpactMessagerie> getAll() {
        return impactMessagerieMapper.toDomains(ListUtils.emptyIfNull(impactMessagerieRepository.findAll()));
    }
}
