package org.wfc.system.controller;


import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 org.wfc.common.core.constant.Constants;
import org.wfc.common.core.constant.GlobalConstants;
import org.wfc.common.core.domain.R;
import org.wfc.common.core.utils.MessageUtils;
import org.wfc.common.core.web.controller.BaseController;
import org.wfc.common.mail.config.properties.MailProperties;
import org.wfc.common.mail.utils.MailUtils;
import org.wfc.common.redis.service.RedisService;

import javax.validation.constraints.NotBlank;
import java.util.concurrent.TimeUnit;

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

    private final MailProperties mailProperties;
    private final RedisService redisService;

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/code")
    public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
        if (!mailProperties.getEnabled()) {
            return R.fail(MessageUtils.message("user.email.not.enable"));
        }
        String key = GlobalConstants.CAPTCHA_CODE_KEY + GlobalConstants.SYSTEM + email;
        String code = RandomUtil.randomNumbers(4);
        redisService.setCacheObject(key, code, Constants.MAIL_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        try {
            MailUtils.sendText(email, "Your WANFI verification code", "Hi\nYour verification code is:\n" + code + "\nThis code will expire in " + Constants.MAIL_CAPTCHA_EXPIRATION + " minutes.\nFor your security, don't share it with anyone.");
        } catch (Exception e) {
            log.error("email verification code send failed => {}", e.getMessage());
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

}
