package com.rdkr.tide_display.backend.firmware.controller;

import com.rdkr.tide_display.backend.gcp.StorageService;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.coyote.BadRequestException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FilesController {

  private final StorageService storageService;

  @GetMapping("/{version:\\d\\.\\d\\.\\d}/{filename:.+}")
  @ResponseBody
  public ResponseEntity<byte[]> download(@PathVariable String version, @PathVariable String filename) {
    byte[] file = storageService.download(version, filename);

    if (file == null) {
      return ResponseEntity.notFound().build();
    }

    return ResponseEntity
        .ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
        .body(file);
  }

  @PostMapping()
  public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
      throws Exception {
    val version = storageService.upload(file);
    if (version == null) {
      throw new BadRequestException("Invalid firmware file");
    }
    redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
    return "redirect:/v1/versions/" + version;
  }
}
