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.CorrespondanceRefEquipement;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.CorrespondanceRefEquipementRepository;
import org.mte.numecoeval.referentiel.infrastructure.mapper.CorrespondanceRefEquipementMapper;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
@AllArgsConstructor
public class CorrespondanceRefEquipementJpaAdapter implements ReferentielPersistencePort<CorrespondanceRefEquipement,String> {

    CorrespondanceRefEquipementMapper mapper;
    CorrespondanceRefEquipementRepository repository;

    @Override
    public CorrespondanceRefEquipement save(CorrespondanceRefEquipement referentiel) throws ReferentielException {
        var entityToSave = mapper.toEntity(referentiel);
        if(entityToSave != null) {
            var entitySaved = repository.save(entityToSave);
            return mapper.toDomain(entitySaved);
        }
        return null;
    }

    @Override
    public void saveAll(Collection<CorrespondanceRefEquipement> referentiels) throws ReferentielException {
        repository.saveAll(ListUtils.emptyIfNull(referentiels
                .stream()
                .map(typeEquipement -> mapper.toEntity(typeEquipement))
                .toList()));
    }

    @Override
    public CorrespondanceRefEquipement get(String id) throws ReferentielException {
        if(id != null) {
            var entityOpt=  repository.findById(id);
            return entityOpt
                    .map(entity -> mapper.toDomain(entity))
                    .orElseThrow(() -> new ReferentielException("Correspondance au RefEquipement "+ id +" non trouvé"));
        }
        throw new ReferentielException("Correspondance au RefEquipement (id null) non trouvé");
    }

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

    @Override
    public List<CorrespondanceRefEquipement> getAll() {

        return ListUtils.emptyIfNull(repository.findAll())
                .stream()
                .map(typeEquipementEntity -> mapper.toDomain(typeEquipementEntity))
                .toList();
    }
}
