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

import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.onl.common.exception.BizException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@RequiredArgsConstructor
public class PortalMainManController extends BaseAnnotationController {

    private final PortalMainManService portalMainManService;

    @GetMapping(value = "/onl/apim/portalmain/portalMainMan.view")
    public void view() {
    }

    @GetMapping(value = "/onl/apim/portalmain/portalMainMan.view", params = "cmd=POPUP")
    public String popup() {
        return "/onl/apim/portalmain/portalMainManPopup";
    }

    /**
     * 포탈 메인 설정 상세 조회
     */
    @PostMapping(value = "/onl/apim/portalmain/portalMainMan.json", params = "cmd=DETAIL")
    public ResponseEntity<PortalMainUI> selectDetail() throws Exception {
        try {
            PortalMainUI mainUI = portalMainManService.loadPortalMain();
            return ResponseEntity.ok(mainUI);
        } catch (Exception e) {
            logger.error(e);
            if (e instanceof BizException) {
                throw e;
            }
            throw new BizException("포탈 메인 설정 조회 중 오류가 발생했습니다. error:" + e.getMessage(), e);
        }
    }

    /**
     * 포탈 메인 설정 저장
     */
    @PostMapping(value = "/onl/apim/portalmain/portalMainMan.json", params = "cmd=INSERT")
    public ResponseEntity<PortalMainUI> insert(PortalMainUI portalMainUI) throws Exception {
        try {
            // Validate input
            if (portalMainUI == null) {
                throw new BizException("입력된 데이터가 없습니다.");
            }

            // Save portal main settings
            portalMainManService.savePortalMain(portalMainUI);

            // Reload and return the saved data
            PortalMainUI savedMainUI = portalMainManService.loadPortalMain();
            return ResponseEntity.ok(savedMainUI);

        } catch (Exception e) {
            logger.error(e);
            if (e instanceof BizException) {
                throw e;
            }
            throw new BizException("포탈 메인 설정 저장 중 오류가 발생했습니다. error:" + e.getMessage(), e);
        }
    }
}
