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

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.eactive.apim.portal.template.entity.MessageCode;
import com.eactive.apim.portal.template.service.MessageHandlerService;
import com.eactive.apim.portal.template.service.MessageRecipient;
import com.eactive.apim.portal.user.entity.UserInfo;
import com.eactive.eai.rms.data.entity.man.user.UserInfoService;
import com.eactive.eai.rms.ext.djb.webhook.dto.WebhookSendRequest;
import com.eactive.eai.rms.ext.djb.webhook.service.WebhookService;

import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class UmsManager {

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

    private final MessageHandlerService messageHandlerService;
    private final UserInfoService userInfoService;
    private final WebhookService webhookService;
    
    /**
     * roleId에 해당하는 역할을 가진 직원에게 UMS(sms,email,messenger) 발송
     * @param role
     * @param messageCode
     * @param params
     * @return
     */
    public void send(String roleId, MessageCode messageCode, HashMap<String, Object> params) {
    	List<UserInfo> users = userInfoService.findAllByRoleId(roleId);
    	if (users.isEmpty()) {
    		log.info("sendMessenger: no users found for role '{}'", roleId);
    		return;
    	}

    	for (UserInfo user : users) {
    		String cleanedPhone = user.getCphnno().replaceAll("[^0-9]", "").trim();
    		MessageRecipient recipient = MessageRecipient.builder()
    				.userId(user.getUserid())
    				.username(user.getUsername())
    				.email(user.getEmad())
    				.phone(cleanedPhone)
    				.messengerId(user.getUserid())
    				.build();
    		messageHandlerService.publishEvent(messageCode, recipient, params);
    	}
    }
    
    /**
     * 직원 또는 회원에게 UMS(sms,email,messenger) 발송
     * @param user
     * @param messageCode
     * @param params
     */
    public void send(UserInfo user, MessageCode messageCode, HashMap<String, Object> params) {
    	String cleanedPhone = user.getCphnno().replaceAll("[^0-9]", "").trim();
    	MessageRecipient recipient = MessageRecipient.builder()
					.userId(user.getUserid())
					.username(user.getUsername())
					.email(user.getEmad())
					.phone(cleanedPhone)
					.messengerId(user.getUserid())
    				.build();
		messageHandlerService.publishEvent(messageCode, recipient, params);
    }
    
    /**
     * event를 구독중인 제휴사에게 웹훅 발송 (비동기)
     * @param event
     * @param apiIds
     */
    @Async("webhookExecutor")
    public void sendWebhook(String event, List<String> apiIds) {
    	List<WebhookSendRequest> list = webhookService.findSendList(event, apiIds);
    	for (WebhookSendRequest req : list) {
    		webhookService.send(req);
    	}
    }
}
