package com.cf.imes.module.system.service.sms;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.enums.UserTypeEnum;
import com.cf.imes.framework.test.core.ut.BaseRedisUnitTest;
import com.cf.imes.module.system.framework.sms.config.SmsCodeConfiguration;
import com.cf.imes.module.system.framework.sms.config.SmsCodeProperties;
import com.cf.imes.module.system.framework.sms.core.client.SmsClient;
import com.cf.imes.module.system.framework.sms.core.client.dto.SmsReceiveRespDTO;
import com.cf.imes.module.system.framework.sms.core.client.dto.SmsSendRespDTO;
import com.cf.imes.module.system.dal.dataobject.sms.SmsTemplateDO;
import com.cf.imes.module.system.mq.message.sms.SmsSendMessage;
import com.cf.imes.module.system.mq.producer.sms.SmsProducer;
import jakarta.annotation.Resource;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.RandomUtil.randomEle;
import static com.cf.imes.framework.test.core.util.AssertUtils.assertServiceException;
import static com.cf.imes.framework.test.core.util.RandomUtils.*;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;

@Import({SmsSendServiceImpl.class, SmsCodeConfiguration.class})
public class SmsSendServiceImplTest extends BaseRedisUnitTest {

    @Resource
    private SmsSendServiceImpl smsSendService;

    @MockitoBean
    private SmsChannelService smsChannelService;
    @MockitoBean
    private SmsTemplateService smsTemplateService;
    @MockitoBean
    private SmsLogService smsLogService;
    @MockitoBean
    private SmsProducer smsProducer;

    @Resource
    private SmsCodeProperties smsCodeProperties;

    @MockitoBean
    private RedisTemplate<String, Object> redisTemplate;

    @MockitoBean
    private ValueOperations<String, Object> valueOperations;


    @BeforeEach
    void setUp() {
        when(redisTemplate.opsForValue()).thenReturn(valueOperations);
    }

    /**
     * 发送成功，当短信模板开启时
     */
    @Test
    void testSendSingleSms_successWhenSmsTemplateEnable() {
        // 准备参数
        String mobile = randomString();
        Long userId = randomLongId();
        Integer userType = randomEle(UserTypeEnum.values()).getValue();
        String templateCode = randomString();
        Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
                .put("op", "login").build();
        // mock SmsTemplateService 的方法
        SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> {
            o.setStatus(CommonStatusEnum.ENABLE.getStatus());
            o.setContent("验证码为{code}, 操作为{op}");
            o.setParams(Lists.newArrayList("code", "op"));
        });
        when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
        String content = randomString();
        when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams)))
                .thenReturn(content);
        // mock SmsLogService 的方法
        Long smsLogId = randomLongId();
        when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(userType), eq(Boolean.TRUE), eq(template),
                eq(content), eq(templateParams))).thenReturn(smsLogId);

        // 调用
        Long resultSmsLogId = smsSendService.sendSingleSms(mobile, userId, userType, templateCode, templateParams);
        // 断言
        assertEquals(smsLogId, resultSmsLogId);
        // 断言调用
        verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(mobile), eq(template),
                eq(Lists.newArrayList(new Pair<>("code", "1234"), new Pair<>("op", "login"))));
    }

    /**
     * 发送成功，当短信模板关闭时
     */
    @Test
    void testSendSingleSms_successWhenSmsTemplateDisable() {
        // 准备参数
        String mobile = randomString();
        Long userId = randomLongId();
        Integer userType = randomEle(UserTypeEnum.values()).getValue();
        String templateCode = randomString();
        Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
                .put("op", "login").build();
        // mock SmsTemplateService 的方法
        SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> {
            o.setStatus(CommonStatusEnum.DISABLE.getStatus());
            o.setContent("验证码为{code}, 操作为{op}");
            o.setParams(Lists.newArrayList("code", "op"));
        });
        when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
        String content = randomString();
        when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams)))
                .thenReturn(content);
        // mock SmsLogService 的方法
        Long smsLogId = randomLongId();
        when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(userType), eq(Boolean.FALSE), eq(template),
                eq(content), eq(templateParams))).thenReturn(smsLogId);

        // 调用
        Long resultSmsLogId = smsSendService.sendSingleSms(mobile, userId, userType, templateCode, templateParams);
        // 断言
        assertEquals(smsLogId, resultSmsLogId);
        // 断言调用
        verify(smsProducer, times(0)).sendSmsSendMessage(anyLong(), any(), any(), anyList());
    }

    @Test
    void testCheckSmsTemplateValid_notExists() {
        // 准备参数
        String templateCode = randomString();
        // mock 方法

        // 调用，并断言异常
        assertServiceException(() -> smsSendService.validateSmsTemplate(templateCode),
                SMS_SEND_TEMPLATE_NOT_EXISTS);
    }

    @Test
    void testBuildTemplateParams_paramMiss() {
        // 准备参数
        SmsTemplateDO template = randomPojo(SmsTemplateDO.class,
                o -> o.setParams(Lists.newArrayList("code")));
        Map<String, Object> templateParams = new HashMap<>();
        // mock 方法

        // 调用，并断言异常
        assertServiceException(() -> smsSendService.buildTemplateParams(template, templateParams),
                SMS_SEND_MOBILE_TEMPLATE_PARAM_MISS, "code");
    }

    @Test
    void testCheckMobile_notExists() {
        // 准备参数
        // mock 方法

        // 调用，并断言异常
        assertServiceException(() -> smsSendService.validateMobile(null),
                SMS_SEND_MOBILE_NOT_EXISTS);
    }

    @Test
    void testSendBatchNotify() {
        // 准备参数
        // mock 方法

        // 调用
        UnsupportedOperationException exception = Assertions.assertThrows(
                UnsupportedOperationException.class,
                () -> smsSendService.sendBatchSms(null, null, null, null, null)
        );
        // 断言
        assertEquals("暂时不支持该操作，感兴趣可以实现该功能哟！", exception.getMessage());
    }

    @Test
    @SuppressWarnings("unchecked")
    void testDoSendSms() throws Throwable {
        // 准备参数
        SmsSendMessage message = randomPojo(SmsSendMessage.class);
        message.setMobile("15601691300");
        message.setTemplateParams(List.of(new Pair<>("code", "123456")));
        // mock SmsClientFactory 的方法
        SmsClient smsClient = mock(SmsClient.class);
        when(smsChannelService.getSmsClient()).thenReturn(smsClient);
        SmsSendRespDTO sendResp = randomPojo(SmsSendRespDTO.class, dto -> dto.setSuccess(true));

        // mock SmsClient 的方法
        when(smsClient.sendSms(eq(message.getLogId()), eq(message.getMobile()), eq(message.getApiTemplateId()),
                eq(message.getTemplateParams()))).thenReturn(sendResp);

        // 调用
        smsSendService.doSendSms(message);

        // 断言
        verify(valueOperations).set(
                contains("sms_captcha_verification"),
                eq("123456"),
                eq(Duration.ofMinutes(5))
        );
        verify(smsLogService).updateSmsSendResult(
                eq(message.getLogId()), eq(true),
                eq(sendResp.getApiCode()), eq(sendResp.getApiMsg()),
                eq(sendResp.getApiRequestId()), eq(sendResp.getSerialNo()), eq(sendResp.getChannelCode())
        );
    }

    @Test
    void testDoSendSms_fail() throws Throwable {
        SmsSendMessage message = randomPojo(SmsSendMessage.class);
        message.setTemplateParams(List.of(new Pair<>("code", "999999")));
        // mock SmsClientFactory 的方法
        SmsClient smsClient = spy(SmsClient.class);
        when(smsChannelService.getSmsClient()).thenReturn(smsClient);
        SmsSendRespDTO sendResp = randomPojo(SmsSendRespDTO.class, dto -> dto.setSuccess(false));
        when(smsClient.sendSms(anyLong(), anyString(), anyString(), anyList())).thenReturn(sendResp);

        smsSendService.doSendSms(message);

        // 不应写 redis
        verify(redisTemplate, never()).opsForValue();
        verify(smsLogService).updateSmsSendResult(
                eq(message.getLogId()), eq(false),
                eq(sendResp.getApiCode()), eq(sendResp.getApiMsg()),
                eq(sendResp.getApiRequestId()), eq(sendResp.getSerialNo()), eq(sendResp.getChannelCode())
        );
    }

    @Test
    void testDoSendSms_throwExceptionDuringSend() throws Throwable {
        SmsSendMessage message = randomPojo(SmsSendMessage.class);
        // mock SmsClientFactory 的方法
        SmsClient smsClient = spy(SmsClient.class);
        when(smsChannelService.getSmsClient()).thenReturn(smsClient);
        when(smsClient.sendSms(anyLong(), anyString(), anyString(), anyList()))
                .thenThrow(new RuntimeException("发送异常"));

        smsSendService.doSendSms(message);

        verify(smsLogService).updateSmsSendResult(
                eq(message.getLogId()), eq(false),
                eq("EXCEPTION"), contains("发送异常"),
                isNull(), isNull(), isNull()
        );
    }



    @Test
    void testReceiveSmsStatus() throws Throwable {
        // 准备参数
        String channelCode = randomString();
        String text = randomString();
        // mock SmsClientFactory 的方法
        SmsClient smsClient = spy(SmsClient.class);
        when(smsChannelService.getSmsClient()).thenReturn(smsClient);
        // mock SmsClient 的方法
        List<SmsReceiveRespDTO> receiveResults = randomPojoList(SmsReceiveRespDTO.class);
        when(smsClient.parseSmsReceiveStatus(text)).thenReturn(receiveResults);

        // 调用
        assertDoesNotThrow(() -> smsSendService.receiveSmsStatus(channelCode, text));
        // 断言
        receiveResults.forEach(result -> smsLogService.updateSmsReceiveResult(eq(result.getLogId()), eq(result.getSuccess()),
                eq(result.getReceiveTime()), eq(result.getErrorCode()), eq(result.getErrorCode())));
    }

}
