package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.model.Hypothese;
import org.mte.numecoeval.referentiel.domain.model.id.HypotheseId;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.HypotheseEntity;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.HypotheseRepository;
import org.mte.numecoeval.referentiel.infrastructure.mapper.HypotheseMapper;
import org.springframework.stereotype.Service;

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


@Service
@Slf4j
@AllArgsConstructor
public class HypotheseJpaAdapter implements ReferentielPersistencePort<Hypothese, HypotheseId> {
    HypotheseRepository hypotheseRepository;

    HypotheseMapper hypotheseMapper;


    @Override
    public Hypothese save(Hypothese referentiel) throws ReferentielException {
        var entityToSave = hypotheseMapper.toEntity(referentiel);
        if(entityToSave != null) {
            var entitySaved = hypotheseRepository.save(entityToSave);
            return hypotheseMapper.toDomain(entitySaved);
        }
        return null;
    }

    @Override
    public void saveAll(Collection<Hypothese> referentiel) throws ReferentielException {
        hypotheseRepository.saveAll(hypotheseMapper.toEntities(referentiel));
    }

    @Override
    public Hypothese get(HypotheseId id) throws ReferentielException {
        Optional<HypotheseEntity> hypotheseOpt = hypotheseRepository.findById(hypotheseMapper.toEntityId(id));
        HypotheseEntity hypotheseEntity = hypotheseOpt.orElseThrow(() -> new ReferentielException("Hypothèse non trouvé"));
        return hypotheseMapper.toDomain(hypotheseEntity);
    }

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

    @Override
    public List<Hypothese> getAll() {
        return hypotheseMapper.fromEntities(hypotheseRepository.findAll());
    }

}
