package com.nexo.resource.controller;


import cn.hutool.core.util.RandomUtil;
import com.nexo.common.core.constant.CacheConstants;
import com.nexo.common.core.constant.Constants;
import com.nexo.common.core.domain.R;
import com.nexo.common.core.web.controller.BaseController;
import com.nexo.common.mail.config.properties.MailProperties;
import com.nexo.common.mail.utils.MailUtils;
import com.nexo.common.redis.utils.RedisUtils;
import com.nexo.system.api.RemoteConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.UUID;

/**
 * 邮件功能
 *
 * @author Lion Li
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/email")
public class SysEmailController extends BaseController {

    private final MailProperties mailProperties;

    @DubboReference
    private final RemoteConfigService remoteConfigService;

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/code")
    public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
        if (!mailProperties.getEnabled()) {
            return R.fail("当前系统没有开启邮箱功能！");
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        String string = UUID.randomUUID().toString();
        RedisUtils.setCacheObject(string, key, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        try {
            String template = remoteConfigService.getConfigKey("auth_code_template");
            if (template == null || template.isEmpty()) {
                log.error("验证码模板配置为空");
                return R.fail("验证码模板配置不存在");
            }
            String content = template.replace("{CODE}", code).replace("{EXPIRE}", String.valueOf(Constants.CAPTCHA_EXPIRATION));

            MailUtils.sendHtml(email, "易盟数科邮箱验证", content);
        } catch (IllegalArgumentException e) {
            log.error("验证码模板格式错误 => {}", e.getMessage(), e);
            return R.fail("验证码模板格式错误");
        } catch (Exception e) {
            log.error("验证码邮件发送异常 => {}", e.getMessage(), e);
            return R.fail("验证码发送失败，请稍后重试");
        }
        return R.ok(string);
    }

}
