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.MixElectrique;
import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId;
import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort;
import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.MixElectriqueDTO;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.MixElectriqueIdDTO;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class MixElectriqueFacade {

    private ReferentielPersistencePort<MixElectrique, MixElectriqueId> persistencePort;

    private MixElectriqueMapper mapper;

    public MixElectriqueDTO get(MixElectriqueIdDTO id) throws ReferentielException {
        MixElectriqueId electriqueId = mapper.toDomainId(id);
        MixElectrique mixElectrique = persistencePort.get(electriqueId);
        return mapper.toDTO(mixElectrique);
    }

    public List<MixElectriqueDTO> getAll() {
        return persistencePort.getAll().stream()
                .map(mix -> mapper.toDTO(mix))
                .toList();
    }

    public List<MixElectriqueDTO> getByPays(String pays) {
        return persistencePort.getAll().stream()
                .filter(mix -> pays.equals(mix.getPays()) || pays.equals(mix.getRaccourcisAnglais()))
                .map(mix -> mapper.toDTO(mix))
                .toList();
    }

    public void purgeAndAddAll(List<MixElectriqueDTO> mixElecs) throws ReferentielException {
        persistencePort.purge();
        persistencePort.saveAll(mapper.toDomainsFromDTO(mixElecs));
    }
}
