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.model.id.CorrespondanceRefEquipementId;
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.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.CorrespondanceRefEquipementIdDTO;
import org.springframework.stereotype.Service;

import java.util.List;

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

    public CorrespondanceRefEquipementDTO get(CorrespondanceRefEquipementIdDTO correspondanceRefEquipementIdDTO) throws ReferentielException {
        CorrespondanceRefEquipement correspondanceRefEquipement = persistencePort.get(mapper.toDomain(correspondanceRefEquipementIdDTO));
        return mapper.toDto(correspondanceRefEquipement);
    }

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

    public void purgeByOrganisationAndAddAll(List<CorrespondanceRefEquipementDTO> correspondances, String nomOrganisation) throws ReferentielException {
        persistencePort.purgeByOrganisation(nomOrganisation);
        persistencePort.saveAll(mapper.toDomains(correspondances));
    }

}
