package com.eactive.ext.kjb.ums.test;

import com.eactive.apim.portal.template.entity.MessageCode;
import com.eactive.apim.portal.template.entity.MessageRequest;
import com.eactive.ext.kjb.common.KjbEaiBatchException;
import com.eactive.ext.kjb.common.KjbProperty;
import com.eactive.ext.kjb.common.KjbPropertyHolder;
import com.eactive.ext.kjb.common.KjbUmsException;
import com.eactive.ext.kjb.ums.KjbEmailSendModule;
import com.eactive.ext.kjb.ums.KjbUmsService;
import com.eactive.ext.kjb.utils.OsUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Slf4j
public class UmsTest {
    private static KjbProperty prop = null;

    @BeforeAll
    public static void init() {
        prop = new KjbProperty();
        prop.setEaiBatchUrl("http://172.31.32.111:10230/BATAppWeb/EaiBatCall");
        prop.setUmsEaiBatchInterfaceId("UIEFF00001UAG");

        prop.setUmsHostUrl("http://172.31.35.144:9021");
        prop.setUmsApiKey("7cca6d58-e4f7-474d-9edd-525806bc99ff");

        if (OsUtil.isWindows()) {
            prop.setEaiBatchUrl("");
            prop.setUmsHostUrl("");
            prop.setUmsEaiBatchSendDir("c:\\kjb-logs\\sendmail\\snd");
            prop.setUmsEaiBatchBackupDir("c:\\kjb-logs\\sendmail\\bak");
            prop.setUmsEaiBatchErrorDir("c:\\kjb-logs\\sendmail\\error");
        }

        if (OsUtil.isLinux()) {
            prop.setUmsEaiBatchSendDir("/Data/eapim/portal/sendmail/snd");
            prop.setUmsEaiBatchBackupDir("/Data/eapim/portal/sendmail/bak");
            prop.setUmsEaiBatchErrorDir("/Data/eapim/portal/sendmail/error");
        }

        KjbPropertyHolder.setForTest(prop);
    }

    @Test
    public void testSms() {
        Assumptions.assumeTrue(
                "true".equalsIgnoreCase(System.getenv("KJB_EAPIM_TEST_ENABLED")),
                "OS 환경변수 내 KJB_EAPIM_TEST_ENABLED=TRUE 설정되어 있어야 동작함");

        MessageRequest messageRequest = new MessageRequest();
        messageRequest.setId(UUID.randomUUID().toString());
        messageRequest.setMessageCode(MessageCode.USER_VERIFICATION_MOBILEPHONE);
        messageRequest.setPhone("01099750188");
        messageRequest.setEmail("dearmai@dearmai.net");
        messageRequest.setUsername("김광은");
        messageRequest.setSubject("제목 - test");
        messageRequest.setMessage("{\"ATHN_NO\"; \"369369\"}");

        KjbUmsService umsService = KjbUmsService.getInstance();
        try {
            boolean result = umsService.send(messageRequest);

        } catch (KjbUmsException e) {
            log.error(e.getMessage(), e);
            Assertions.fail(e);
            return;
        }

        log.info("done");
    }

    /**
     * :eapim-admin-kjb:test --tests "com.eactive.ext.kjb.ums.test.UmsTest.testEmail"
     */
    @Test
    public void testEmail() {
        Assumptions.assumeTrue(
                "true".equalsIgnoreCase(System.getenv("KJB_EAPIM_TEST_ENABLED")),
                "OS 환경변수 내 KJB_EAPIM_TEST_ENABLED=TRUE 설정되어 있어야 동작함");


        System.getProperties().keySet().forEach(key -> {
            log.info("{}: {}", key, System.getProperty((String) key));
        });

        KjbEmailSendModule service = KjbEmailSendModule.getInstance();

        List<MessageRequest> requestList = new ArrayList<>();


        log.info("#1 요청 생성 - 이메일 인증");
        requestList.add(createMessageRequest(MessageCode.USER_VERIFICATION_EMAIL, "{\"ATHN_NO\": \"543216\"}"));

        log.info("#2 요청 생성 - 비밀번호 초기화");
        requestList.add(createMessageRequest(MessageCode.USER_PASSWORD_RESET, "{\"ATHN_NO\": \"new-password\"}"));

        log.info("#3 요청 생성 - 비밀번호 변경 완료");
        requestList.add(createMessageRequest(MessageCode.USER_PASSWORD_CHANGED, ""));

        log.info("#4 요청 생성 - 로그인 제한");
        requestList.add(createMessageRequest(MessageCode.USER_ACCOUNT_LOCKED, "{\"RJCT_RSN\": \"reason\"}"));

        log.info("#5 요청 생성 - 이메일 초대");
        requestList.add(createMessageRequest(MessageCode.USER_INVITATION,
                "{\"CRPT_NM\":\"corpName\",\"MNGR_NM\":\"managerName\",\"CUST_ID\":\"loginId\",\"RCMD_CD\":\"321654\",\"URL_ADDR\":\"https://www.naver.com/\"}"));

        log.info("#6 요청 생성 - 이메일 초대 취소");
        requestList.add(createMessageRequest(MessageCode.USER_INVITATION_CANCELED,
                "{\"CRPT_NM\":\"corpName\",\"MNGR_NM\":\"managerName\"}"));

        log.info("#7 요청 생성 - 법인관리자 및 법인 등록 승인");
        requestList.add(createMessageRequest(MessageCode.MANAGER_WITH_ORG_REGISTER_APPROVED, ""));

        log.info("#8 요청 생성 - 법인관리자 및 법인 등록 거절");
        requestList.add(createMessageRequest(MessageCode.MANAGER_WITH_ORG_REGISTER_REJECTED, "{\"RJCT_RSN\": \"reason\"}"));

        log.info("#9 요청 생성 - 앱 승인");
        requestList.add(createMessageRequest(MessageCode.APP_REGISTER_APPROVED, "{\"APP_IDNT_NM\": \"appName\"}"));

        log.info("#10 요청 생성 - 앱 승인 거절");
        requestList.add(createMessageRequest(MessageCode.APP_REGISTER_REJECTED, "{\"RJCT_RSN\": \"reason\"}"));



        try {
            for (int i = 0; i < requestList.size(); i++) {
                MessageRequest request = requestList.get(i);
                log.info("#{} - 메일 전송 시도 - {}", i + 1, request.getServiceId());
                service.sendEmail(request);
            }
        } catch (KjbEaiBatchException e) {
            throw new RuntimeException(e);
        }

        log.info("done");
    }

    private MessageRequest createMessageRequest(MessageCode messageCode, String message) {
        MessageRequest messageRequest = new MessageRequest();
        messageRequest.setId(UUID.randomUUID().toString());
        messageRequest.setMessageCode(messageCode);
        messageRequest.setEmail(System.getenv().getOrDefault("KJB_TEST_EMAIL", "25W0064@kjbank.com"));
        messageRequest.setUmsUid(UUID.randomUUID().toString());
        messageRequest.setUsername("김광은");
        messageRequest.setSubject("제목 - test");
        messageRequest.setMessage(message);
//        messageRequest.setServiceId(serviceId);

        log.info("MessageRequest - {}", messageRequest);

        return messageRequest;
    }
}
