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.model.id.TypeItemId;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.TypeItemEntity;
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;
import java.util.Optional;

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

    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(TypeItemId id) throws ReferentielException {
        Optional<TypeItemEntity> typeItemOpt = typeItemRepository.findById(typeItemMapper.toEntityId(id));
        TypeItemEntity typeItemEntity = typeItemOpt.orElseThrow(() -> new ReferentielException("Type Item non trouvé pour l'id " + id));
        return typeItemMapper.toDomain(typeItemEntity);
    }

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

    @Override
    public void purgeByOrganisation(String nomOrganisation) {
        typeItemRepository.deleteByNomOrganisation(nomOrganisation);
    }

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