package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese;

import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportHypothesePortImpl;
import org.mte.numecoeval.referentiel.infrastructure.adapter.export.HypotheseCsvExportService;
import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.HypotheseEntity;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.BaseExportReferentiel;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.HypotheseDTO;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.HypotheseIdDTO;
import org.mte.numecoeval.referentiel.infrastructure.restapi.facade.HypotheseFacade;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;

@RestController
@Slf4j
@AllArgsConstructor
public class ReferentielHypotheseRestApiImpl implements BaseExportReferentiel<HypotheseEntity>, ReferentielAdministrationHypotheseRestApi, ReferentielHypotheseRestApi {
    private HypotheseFacade referentielFacade;

    private HypotheseCsvExportService csvExportService;

    @Override
    public RapportImportDTO importCSV(MultipartFile fichier) throws IOException, ReferentielException {
        if (fichier == null || fichier.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Le fichier n'existe pas ou alors il est vide");
        }
        var rapportImport = new ImportHypothesePortImpl().importCSV(fichier.getInputStream());
        referentielFacade.purgeAndAddAll(rapportImport.getObjects());

        return new RapportImportDTO(
                fichier.getOriginalFilename(),
                rapportImport.getErreurs(),
                rapportImport.getNbrLignesImportees()
        );
    }

    @SneakyThrows
    @Override
    public HypotheseDTO get(String cle) {
        HypotheseIdDTO hypotheseIdDTO = new HypotheseIdDTO();
        hypotheseIdDTO.setCode(cle);
        return referentielFacade.get(hypotheseIdDTO);
    }

    @Override
    public void exportCSV(HttpServletResponse servletResponse) throws IOException {
        exportCSV(servletResponse, csvExportService, "hypotheses");
    }
}
