package com.eactive.eai.rms.ext.djb.apistatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.apim.portal.template.entity.MessageCode;
import com.eactive.eai.rms.data.entity.man.role.Role;
import com.eactive.eai.rms.data.entity.onl.djb.apistatus.ApiStatus;
import com.eactive.eai.rms.data.entity.onl.djb.apistatus.ApiStatusEvent;
import com.eactive.eai.rms.ext.djb.ums.UmsManager;


@Service
@Transactional
public class ApiStatusService {

    private static final Logger log = LoggerFactory.getLogger(ApiStatusService.class);

    @Autowired
    private ApiStatusRepository apiStatusRepository;

    @Autowired
    private UmsManager ums;

    @Autowired
    private ApiStatusDetectionService apiStatusDectionService;
    
    
    public void updateApiStatus(HashMap<String, String> param) {
    	
        List<ApiStatusEvent> list = apiStatusRepository.findApiStatusEvents(
            Integer.parseInt(param.get("errorRate")),
            Integer.parseInt(param.get("errorRangeMinute")),
            Integer.parseInt(param.get("delayRangeMinute")),
            Integer.parseInt(param.get("delayAvgRespTime"))
        );
        
        HashMap<String, List<String>> eventMap = new HashMap<>();
        
        
        for (ApiStatusEvent event : list) {
        	String newStatusCode = resolveStatusCode(event.getEvent());
            if (newStatusCode == null) continue;

            ApiStatus apiStatus = apiStatusRepository.findById(event.getEaisvcname()).orElse(new ApiStatus());

            apiStatus.setEaisvcname(event.getEaisvcname());
            apiStatus.setStatusCode(newStatusCode);

            apiStatusRepository.saveAndFlush(apiStatus);  // PK 있으면 UPDATE, 없으면 INSERT (즉시 flush)
            
            log.debug("API 상태 변경: {}-{} {} → {}", event.getEaisvcname(), event.getEaisvcdesc(), event.getEvent(), newStatusCode);
            
        	
            //이벤트별로 api분리 저장
            List<String> apis = (List<String>)eventMap.get(event.getEvent());
            if (apis == null) {
            	apis = new ArrayList<String>();
            	apis.add(event.getEaisvcname());
            	eventMap.put(event.getEvent(), apis);
            } else {
            	apis.add(event.getEaisvcname());
            }
        }
        
        //이벤트별로 ums, webhook을 발송한다
        for (Map.Entry<String, List<String>> entry : eventMap.entrySet()) {
        	String event = entry.getKey();
			List<String> apiIds = entry.getValue();
			
			HashMap<String, Object> params = getSwingChatMessage(event, apiIds);
			ums.send("api-monitor", MessageCode.API_STATUS_CHANGED, params);

            //제휴사 웹훅 발송
            ums.sendWebhook(event, apiIds);

            //개발자포탈 API상태모니터링 화면을 위한 처리
            apiStatusDectionService.detect(event, apiIds);
        }
    }
    
    
    private String resolveStatusCode(String event) {
        switch (event) {
            case "CONTROL_START": return "C";	//점검
            case "CONTROL_END":   return "N";	//정상
            case "ERROR_START":   return "E";	//장애
            case "ERROR_END":     return "N";	//정상
            case "DELAY_START":   return "D";	//지연
            case "DELAY_END":     return "N";	//정상
            default:
                log.warn("알 수 없는 이벤트: {}", event);
                return null;
        }
	}
    
    
    private HashMap<String, Object> getSwingChatMessage(String event, List<String> apiIds) {
    	String message = "";
    	switch (event) {
	        case "CONTROL_START": 
	        	message = "API 서비스 점검이 시작되었습니다";	//점검	
	        	break;
	        case "CONTROL_END":   
	        	message = "API 서비스 점검이 완료되었습니다";	//정상
	        	break;
	        case "ERROR_START":   
	        	message = "API 서비스 장애가 발생하였습니다";	//장애
	        	break;
	        case "ERROR_END":     
	        	message = "API 서비스 장애가 복구되었습니다";	//정상
	        	break;
	        case "DELAY_START":   
	        	message = "API 서비스 지연이 발생하였습니다";	//지연
	        	break;
	        case "DELAY_END":     
	        	message = "API 서비스 지연이 복구되었습니다";	//정상
	        	break;
	        default:
	        	message = "";
	    }
    	
    	if (apiIds.size() > 1) {
    		message += "\n" + apiIds.get(0) + "외 " + (apiIds.size()-1) + "종"; 
    	} else {
    		message += "\n- " + apiIds.get(0);
    	}
    	
    	HashMap<String, Object> params = new HashMap<>();
		params.put("message", message);
		
		return params;
    }
}

