package org.mte.numecoeval.referentiel.infrastructure.restapi.facade;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactMessagerieDTO;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielRuntimeException;
import org.mte.numecoeval.referentiel.domain.model.ImpactMessagerie;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactMessagerieMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ImpactMessagerieFacade {
    private ReferentielPersistencePort<ImpactMessagerie, String> persistencePort;
    private ImpactMessagerieMapper mapper;

    public ImpactMessagerieFacade(ReferentielPersistencePort<ImpactMessagerie, String> persistencePort, ImpactMessagerieMapper mapper) {
        this.persistencePort = persistencePort;
        this.mapper = mapper;
    }

    public ImpactMessagerieDTO getImpactMessagerieForCritere(String critere) {
        try {
            var impactMessagerie = persistencePort.get(critere);
            return mapper.toDTO(impactMessagerie);
        } catch (Exception e) {
            log.error("Erreur lors de l'accès à l'impact Messagerie : Critère : {} : {}", critere, e.getMessage());
            throw new ReferentielRuntimeException(e.getMessage());
        }
    }

    public List<ImpactMessagerieDTO> getAllImpactMessagerie() {
        List<ImpactMessagerie> domains = persistencePort.getAll();
        return ListUtils.emptyIfNull(mapper.toDTOs(domains));
    }

    public void purgeAndAddAll(List<ImpactMessagerieDTO> dtos) throws ReferentielException {
        persistencePort.purge();
        persistencePort.saveAll(mapper.toDomainsFromDTO(dtos));
    }

}
