package com.ffii.core.user.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ffii.core.exception.NotFoundException;
import com.ffii.core.response.DataRes;
import com.ffii.core.support.AbstractController;
import com.ffii.core.user.service.UserService;
import com.ffii.core.user.service.UserSignService;

@RestController
@RequestMapping("/protected/user/{userId}/sign")
public class UserSignController extends AbstractController {

  private UserService userService;
  private UserSignService userSignService;

  public UserSignController(UserService userService, UserSignService userSignService) {
    this.userService = userService;
    this.userSignService = userSignService;
  }

  @PostMapping
  // @PreAuthorize("hasAuthority('USER_MAINTAIN')")
  @ResponseStatus(HttpStatus.CREATED)
  public void saveSign(HttpServletRequest request, @PathVariable int userId, @RequestParam MultipartFile userSign) throws IOException {
    if (userService.find(userId).isEmpty()) {
      throw new NotFoundException();
    }
    userSignService.saveSign(userId, userSign);
  }

  @GetMapping
  // @PreAuthorize("hasAuthority('USER_MAINTAIN')")
  public DataRes<Map<String, Object>> findSign(@PathVariable int userId) {
    return new DataRes<>(userSignService.findUserSignatureMap(userId).orElseThrow(NotFoundException::new));
  }
}
