package de.accso.flexinale.rest;

import de.accso.flexinale.data.services.ExcelDataUploadService;
import de.accso.flexinale.data.services.PersistMode;
import de.accso.flexinale.shared_kernel.ExcelHelper;
import de.accso.flexinale.shared_kernel.FlexinaleIllegalStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.util.Collection;

abstract class AbstractExcelRestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractExcelRestController.class);

    @SuppressWarnings("rawtypes")
    protected RestUploadResult uploadViaRestCall(final ExcelDataUploadService excelDataUploadService, final MultipartFile file) {
        try(BufferedInputStream stream = new BufferedInputStream(file.getInputStream())) {
            if (!ExcelHelper.isExcelFile(stream)) {
                String message = "Please upload a valid Excel file!";
                throw new FlexinaleIllegalStateException(message);
            }

            Collection uploadedData =
                    excelDataUploadService.loadDataFromExcelSheetAndPersistAndReturn(stream, PersistMode.ADD_ONLY);

            String message = "Uploaded the Excel file %s adding %d new entities (while not updating any existing data)."
                    .formatted(file.getOriginalFilename(), uploadedData.size());

            return new RestUploadResult(HttpStatus.OK, message);
        }
        catch (Exception ex) {
            String message = "Could not upload the Excel file: %s: %s".formatted(file.getOriginalFilename(), ex.getMessage());
            RestBadRequestException exception = new RestBadRequestException(message, ex);
            LOGGER.error(message, exception);

            throw exception;
        }
    }
}
