package com.eactive.eai.rms.onl.manage.authserver.client;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.authserver.ClientSearch;
import com.eactive.eai.rms.onl.httpouttlsinfo.HttpOutTlsInfoManService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.SortDefault;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.HashMap;
import java.util.Map;

@Controller
public class ClientController extends OnlBaseAnnotationController {

    private ClientManService clientManService;
    private HttpOutTlsInfoManService httpOutTlsInfoManService;

    @Autowired
    public ClientController(ClientManService clientManService, HttpOutTlsInfoManService httpOutTlsInfoManService) {
        this.clientManService = clientManService;
        this.httpOutTlsInfoManService = httpOutTlsInfoManService;
    }

    @GetMapping(value = "/onl/admin/authserver/clientMan.view")
    public void view() {
        // view
    }

    @GetMapping(value = "/onl/admin/authserver/clientMan.view", params = "cmd=GROUP_POPUP")
    public String apiSearchGroupPopup() {
        return "/onl/admin/authserver/clientManGroupPopup";
    }

    @GetMapping(value = "/onl/admin/authserver/clientMan.view", params = "cmd=DETAIL")
    public String viewList() {
        return "/onl/admin/authserver/clientManDetail";
    }

    @GetMapping(value = "/onl/admin/authserver/clientMan.view", params = "cmd=POPUP")
    public String viewPopup() {
        return "/onl/admin/authserver/clientManPopup";
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=LIST")
    public ResponseEntity<GridResponse<ClientUI>> selectList(@SortDefault("clientname") Pageable pageable,
        ClientSearch clientSearch) {
        Page<ClientUI> page = clientManService.selectList(pageable, clientSearch);
        return ResponseEntity.ok(new GridResponse<>(page));
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=POPUP_LIST")
    public ResponseEntity<GridResponse<ClientUI>> selectPopupList(@SortDefault("clientname") Pageable pageable,
        ClientSearch clientSearch) {
        Page<ClientUI> page = clientManService.selectList(pageable, clientSearch);
        return ResponseEntity.ok(new GridResponse<>(page));
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=LIST_DETAIL_COMBO")
    public ResponseEntity<Map<String, Object>> selectDetailCombo() throws Exception {
        Map<String, Object> map = clientManService.selectDetailCombo();
        return ResponseEntity.ok(map);
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=DETAIL")
    public ResponseEntity<ClientUI> selectDetail(String clientId) {
        ClientUI clientUI = clientManService.selectDetail(clientId);
        return ResponseEntity.ok(clientUI);
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=INSERT")
    public ResponseEntity<Void> insert(ClientUI clientUI) {
        clientManService.insert(clientUI);

        CommonCommand.builder()
            .name(CommonCommand.RELOAD_CLIENT_COMMAND)
            .args(clientUI.getClientId())
            .build().broadcast(agentUtilService);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=UPDATE")
    public ResponseEntity<Void> update(ClientUI clientUI) {
        clientManService.update(clientUI);

        CommonCommand.builder()
            .name(CommonCommand.RELOAD_CLIENT_COMMAND)
            .args(clientUI.getClientId())
            .build().broadcast(agentUtilService);

        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=DELETE")
    public ResponseEntity<Void> delete(String clientId) {
        clientManService.delete(clientId);

        CommonCommand.builder()
            .name(CommonCommand.RELOAD_CLIENT_COMMAND)
            .args(clientId)
            .build().broadcast(agentUtilService);

        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=CHECKMTLS")
    public ResponseEntity<Map<String, Object>> checkMtls(String clientId) {
        Map<String, Object> response = new HashMap<>();

        boolean hasMtls = httpOutTlsInfoManService.existsById(clientId);
        response.put("hasMtls", hasMtls);
        return ResponseEntity.ok(response);
    }

    /**
     * APIGW 인증관리 정보를 개발자포탈에 반영합니다.
     * 포탈에 없으면 신규 생성, 있으면 업데이트합니다.
     *
     * @param clientId 클라이언트 ID
     * @return 반영 결과 (success, action, message, invalidApis)
     */
    @PostMapping(value = "/onl/admin/authserver/clientMan.json", params = "cmd=SYNC_PORTAL")
    public ResponseEntity<Map<String, Object>> syncPortalData(String clientId) {
        try {
            SyncResult result = clientManService.syncPortalData(clientId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            response.put("action", result.getAction().name());

            // 반영 대상 API 목록 포함
            if (result.getTargetApis() != null) {
                response.put("targetApis", result.getTargetApis());
                response.put("targetApiCount", result.getTargetApiCount());
            }

            // 반영된 API 목록 포함
            if (result.getSyncedApis() != null) {
                response.put("syncedApis", result.getSyncedApis());
                response.put("syncedApiCount", result.getSyncedApiCount());
            }

            // 유효하지 않는 API 목록 포함 (사유: APIGW에 미존재)
            if (result.getInvalidApis() != null && !result.getInvalidApis().isEmpty()) {
                response.put("invalidApis", result.getInvalidApis());
            }

            // 자동 생성된 API Spec 목록 포함
            if (result.getCreatedApiSpecs() != null && !result.getCreatedApiSpecs().isEmpty()) {
                response.put("createdApiSpecs", result.getCreatedApiSpecs());
                response.put("createdApiSpecCount", result.getCreatedApiSpecCount());
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 에러 처리
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "반영 중 오류: " + e.getMessage());
            error.put("action", "ERROR");
            return ResponseEntity.status(500).body(error);
        }
    }
}
