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

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

@Service
@Slf4j
@AllArgsConstructor
public class TypeItemJpaAdapter implements ReferentielPersistencePort<TypeItem, String> {

    TypeItemMapper typeItemMapper;
    TypeItemRepository typeItemRepository;

    @Override
    public TypeItem save(TypeItem typeItem) throws ReferentielException {
        typeItemRepository.save(typeItemMapper.toEntity(typeItem));
        return typeItem;
    }

    @Override
    public void saveAll(Collection<TypeItem> referentiels) throws ReferentielException {
        if (referentiels == null) return;

        typeItemRepository.saveAll(referentiels.stream()
                .map(TypeItem -> typeItemMapper.toEntity(TypeItem))
                .toList());
    }

    @Override
    public TypeItem get(String id) throws ReferentielException {
        return typeItemRepository.findById(id)
                .map(typeItemEntity -> typeItemMapper.toDomain(typeItemEntity))
                .orElse(null);
    }

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

    @Override
    public List<TypeItem> getAll() {
        return typeItemRepository.findAll()
                .stream()
                .map(TypeItemEntity -> typeItemMapper.toDomain(TypeItemEntity))
                .toList();
    }
}