package com.cloudhandson.vpdbackoffice.web;

import com.cloudhandson.vpdbackoffice.service.AppException;
import com.cloudhandson.vpdbackoffice.service.MaskingRuleService;
import com.cloudhandson.vpdbackoffice.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class UserMaskingRuleController {

  private final MaskingRuleService maskingRuleService;
  private final UserService userService;

  public UserMaskingRuleController(MaskingRuleService maskingRuleService, UserService userService) {
    this.maskingRuleService = maskingRuleService;
    this.userService = userService;
  }

  @GetMapping("/user-masking-rules")
  public String userMaskingRules(Model model) {
    model.addAttribute("users", userService.findAll());
    model.addAttribute("columnRules", maskingRuleService.findColumnRules().stream()
        .filter(columnRule -> columnRule.ruleEnabled())
        .toList());
    model.addAttribute("userRules", maskingRuleService.findUserRules());
    return "user-masking-rules";
  }

  @PostMapping("/user-masking-rules")
  public String assign(
      @RequestParam long userId,
      @RequestParam long columnId,
      RedirectAttributes redirectAttributes
  ) {
    try {
      maskingRuleService.assignUserRule(userId, columnId, "UNMASK");
      redirectAttributes.addFlashAttribute("message", "컬럼 원문 표시 허용 사용자를 저장했습니다. 이 설정은 행 접근 권한을 추가하지 않습니다.");
    } catch (AppException exception) {
      redirectAttributes.addFlashAttribute("errorMessage", exception.getMessage());
    }
    return "redirect:/user-masking-rules";
  }

  @PostMapping("/user-masking-rules/delete")
  public String remove(
      @RequestParam long userId,
      @RequestParam long columnId,
      RedirectAttributes redirectAttributes
  ) {
    try {
      maskingRuleService.removeUserRule(userId, columnId);
      redirectAttributes.addFlashAttribute("message", "컬럼 원문 표시 허용을 해제하고 컬럼의 기본 컬럼 마스킹 규칙으로 되돌렸습니다.");
    } catch (AppException exception) {
      redirectAttributes.addFlashAttribute("errorMessage", exception.getMessage());
    }
    return "redirect:/user-masking-rules";
  }
}
