package com.fsd.hellovelo.controller;

import com.amazonaws.AmazonClientException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.fsd.hellovelo.exceptions.ResourceNotFoundException;
import com.fsd.hellovelo.payload.request.UserReportRequest;
import com.fsd.hellovelo.payload.response.MessageResponse;
import com.fsd.hellovelo.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.validation.Valid;
import java.io.IOException;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/reports")
@PreAuthorize("hasRole('USER')")
public class ReportUserController {

    private final ReportService reportService;

    @Autowired
    public ReportUserController(ReportService reportService) {
        this.reportService = reportService;
    }

    @PostMapping(consumes = {"multipart/form-data"})
    public ResponseEntity<?> sendReport(@Valid UserReportRequest userReportRequest,
                                        @RequestParam(value = "file",required = false) MultipartFile file
                                        ) {
        try {
            reportService.sendReport(userReportRequest, file);
            return ResponseEntity.status(HttpStatus.OK).body(new MessageResponse("Your report was sent!"));
        }
        catch (ResourceNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new MessageResponse(e.getMessage()));
        }
        catch (IOException | SdkClientException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new MessageResponse("An error occurred while uploading your file"));
        }
        catch(IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new MessageResponse(e.getMessage()));

        }
    }


}
