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

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.model.CorrespondanceRefEquipement;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.mapper.CorrespondanceRefEquipementMapper;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.CorrespondanceRefEquipementDTO;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class CorrespondanceRefEquipementFacade {
    private ReferentielPersistencePort<CorrespondanceRefEquipement, String> persistencePort;
    private CorrespondanceRefEquipementMapper mapper;

    public CorrespondanceRefEquipementDTO get(String modeleEquipementSource) throws ReferentielException {
        var correspondanceRefEquipement = persistencePort.get(modeleEquipementSource);
        if (correspondanceRefEquipement != null) {
            return mapper.toDto(correspondanceRefEquipement);
        }
        return null;
    }

    public List<CorrespondanceRefEquipementDTO> getAll() {
        List<CorrespondanceRefEquipement> domains = persistencePort.getAll();
        return CollectionUtils.emptyIfNull(domains).stream().map(domain -> mapper.toDto(domain)).toList();
    }

    public void purgeAndAddAll(List<CorrespondanceRefEquipementDTO> correspondances) throws ReferentielException {
        persistencePort.purge();
        persistencePort.saveAll(CollectionUtils.emptyIfNull(correspondances).stream()
                .map(dto -> mapper.toDomain(dto))
                .toList());
    }

}
