package org.mte.numecoeval.referentiel.infrastructure.restapi.facade;

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.mapper.TypeItemMapper;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.TypeItemDTO;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class TypeItemFacade {

    private ReferentielPersistencePort<TypeItem, String> persistencePort;
    private TypeItemMapper mapper;

    public TypeItemDTO getTypeItemForType(String type) throws ReferentielException {
        var TypeItem = persistencePort.get(type);
        if (TypeItem != null) {
            return mapper.toDTO(TypeItem);
        }
        return null;
    }

    public List<TypeItemDTO> getAllTypesItem() {
        return persistencePort.getAll().stream()
                .map(TypeItem -> mapper.toDTO(TypeItem))
                .toList();
    }

    public void purgeAndAddAll(List<TypeItemDTO> types) throws ReferentielException {
        if (types == null) return;
        persistencePort.purge();
        persistencePort.saveAll(types.stream()
                .map(TypeItemDTO -> mapper.toDomain(TypeItemDTO))
                .toList());
    }

}
