package com.eactive.eai.rms.onl.apim.approval;

import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.apim.approval.PortalApprovalUISearch;
import com.eactive.eai.rms.onl.common.exception.BizException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequiredArgsConstructor
public class PortalApprovalManController extends BaseAnnotationController {

    private final PortalApprovalManService portalApprovalManService;

    @GetMapping(value = "/onl/apim/approval/portalApprovalMan.view")
    public void view(Model model) {
        model.addAttribute("hardDeleteEnabled", portalApprovalManService.isHardDeleteEnabled());
    }

    @GetMapping(value = "/onl/apim/approval/portalApprovalMan.view", params = "cmd=DETAIL")
    public String detailView(@RequestParam(name = "type", defaultValue = "app") String type) {
        if (type.equalsIgnoreCase("app")) {
            return "/onl/apim/approval/portalAppApprovalManPopup";
        } else {
            return "/onl/apim/approval/portalUserApprovalManPopup";
        }
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=LIST")
    public ResponseEntity<GridResponse<PortalApprovalUI>> selectList(@SortDefault(value = "createdDate", direction = Sort.Direction.DESC) Pageable pageable,
        PortalApprovalUISearch portalApprovalUISearch) {
        Page<PortalApprovalUI> page = portalApprovalManService.selectList(pageable, portalApprovalUISearch);
        return ResponseEntity.ok(new GridResponse<>(page));
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=DETAIL")
    public ResponseEntity<PortalApprovalUI> selectDetail(String id) {
        PortalApprovalUI portalApprovalUI = portalApprovalManService.selectDetail(id);
        return ResponseEntity.ok(portalApprovalUI);
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=UNMASK")
    public ResponseEntity<PortalApprovalUI> selectDetail(String id, String reason) {
        if (StringUtils.isBlank(reason)) {
            throw new BizException("마스킹 해제 사유를 입력해 주세요.");
        }
        PortalApprovalUI portalApprovalUI = portalApprovalManService.selectDetailUnmask(id);
        return ResponseEntity.ok(portalApprovalUI);
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=APPROVE")
    public ResponseEntity<Void> approve(String id) {
        portalApprovalManService.approve(id, SessionManager.getLoginVo().getUserId());
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=REJECT")
    public ResponseEntity<Void> reject(String id, String rejectReason) {
        portalApprovalManService.reject(id, SessionManager.getLoginVo().getUserId(), rejectReason);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=REDEPLOY")
    public ResponseEntity<Void> redeploy(String id) {
        portalApprovalManService.redeploy(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=HARD_DELETE_MULTIPLE")
    public ResponseEntity<Map<String, Object>> hardDeleteMultiple(String ids) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(ids)) {
                resultMap.put("status", "fail");
                resultMap.put("message", "삭제할 승인 요청을 선택해주세요.");
                return ResponseEntity.ok(resultMap);
            }

            String[] idArray = ids.split(",");
            int successCount = 0;
            List<String> failMessages = new ArrayList<>();

            for (String id : idArray) {
                if (StringUtils.isNotBlank(id.trim())) {
                    try {
                        portalApprovalManService.hardDelete(id.trim());
                        successCount++;
                    } catch (BizException e) {
                        failMessages.add(e.getMessage());
                    } catch (Exception e) {
                        failMessages.add(id.trim() + ": " + e.getMessage());
                    }
                }
            }

            if (failMessages.isEmpty()) {
                resultMap.put("status", "success");
                resultMap.put("message", successCount + "건의 승인 요청이 완전삭제되었습니다.");
            } else {
                resultMap.put("status", "fail");
                resultMap.put("message", "완전삭제 실패: " + String.join(", ", failMessages)
                        + (successCount > 0 ? " (" + successCount + "건 성공)" : ""));
            }
        } catch (Exception e) {
            resultMap.put("status", "fail");
            resultMap.put("message", "완전삭제 중 오류가 발생했습니다: " + e.getMessage());
        }
        return ResponseEntity.ok(resultMap);
    }

    @PostMapping(value = "/onl/apim/approval/portalApprovalMan.json", params = "cmd=UPDATE")
    public ResponseEntity<Void> update(String id, String expectEndDate) {
        portalApprovalManService.update(id, expectEndDate);
        return ResponseEntity.ok().build();
    }
}
