package de.accso.flexinale.backoffice.api_in.rest;

import de.accso.flexinale.backoffice.api_out.event.VorfuehrungPublisher;
import de.accso.flexinale.backoffice.application.services.VorfuehrungUploadService;
import de.accso.flexinale.backoffice.domain.model.Vorfuehrung;
import de.accso.flexinale.backoffice.application.services.VorfuehrungService;
import de.accso.flexinale.common.application.PersistMode;
import de.accso.flexinale.common.application.PersistedEntityAndResult;
import de.accso.flexinale.common.shared_kernel.FlexinaleIllegalStateException;
import de.accso.flexinale.common.shared_kernel.Identifiable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

import static de.accso.flexinale.common.application.PersistedEntityAndResult.PersistedResult.ADDED;
import static de.accso.flexinale.common.application.PersistedEntityAndResult.PersistedResult.UPDATED;

@RestController
@Profile({ "!testdata-besucherportal & !testdata-ticketing" })
public class VorfuehrungRestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(VorfuehrungRestController.class);

    @Autowired
    private VorfuehrungService vorfuehrungService;

    @Autowired
    private VorfuehrungUploadService vorfuehrungUploadService;

    @Autowired
    private VorfuehrungPublisher vorfuehrungPublisher;

    @GetMapping(value = "/rest/vorfuehrungen", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_BESUCHER')")
    public List<Vorfuehrung> vorfuehrungen() {
        return vorfuehrungService.vorfuehrungen();
    }

    @GetMapping(value = "/rest/vorfuehrungen/{id}", produces = "application/json")
    @PreAuthorize("hasRole('ROLE_BESUCHER')")
    public Vorfuehrung vorfuehrung(@PathVariable final String id) {
        Identifiable.Id vorfuehrungId = Identifiable.Id.of(id);
        Vorfuehrung vorfuehrung = vorfuehrungService.vorfuehrung(vorfuehrungId);
        if (vorfuehrung == null) {
            throw new RestResourceNotFoundException("no Vorfuehrung %s found.".formatted(id));
        }

        return vorfuehrung;
    }

    // -----------------------------------------------------------------------------------------------------------

    @PostMapping("/rest/vorfuehrungen")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<RestResponseMessage> uploadVorfuehrungen(@RequestParam("file") 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);
            }

            return loadAndPersistAndPublishNewVorfuehrungen(stream, file.getOriginalFilename());
        }
        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;
        }
    }

    ResponseEntity<RestResponseMessage> loadAndPersistAndPublishNewVorfuehrungen(
            final BufferedInputStream stream, final String originalFilename) throws IOException
    {
        // load and persist
        Collection<PersistedEntityAndResult<Vorfuehrung>> addedAndUpdatedVorfuehrungen =
                vorfuehrungUploadService.loadDataFromExcelSheetAndPersistAndReturn(stream, PersistMode.UPDATE);

        // publish as events
        List<Vorfuehrung> addedVorfuehrungen = addedAndUpdatedVorfuehrungen.stream()
                .filter(vorfuehrungWithResult -> vorfuehrungWithResult.result().equals(ADDED))
                .map(PersistedEntityAndResult::entity)
                .toList();
        vorfuehrungPublisher.publishNewVorfuehrungen(addedVorfuehrungen);
        List<Vorfuehrung> updatedVorfuehrungen = addedAndUpdatedVorfuehrungen.stream()
                .filter(vorfuehrungWithResult -> vorfuehrungWithResult.result().equals(UPDATED))
                .map(PersistedEntityAndResult::entity)
                .toList();
        vorfuehrungPublisher.publishUpdatedVorfuehrungen(updatedVorfuehrungen);

        String message = "Uploaded the Excel file %s adding %d new Vorfuehrungen entities and updating %d existing Vorfuehrungen entities."
                .formatted(originalFilename, addedVorfuehrungen.size(), updatedVorfuehrungen.size());

        RestUploadResult restUploadResult = new RestUploadResult(HttpStatus.OK, message);
        return ResponseEntity.status(restUploadResult.status())
                .body(new RestResponseMessage(restUploadResult.message()));
    }
}
