package com.izouma.nineth.web;

import com.izouma.nineth.config.Constants;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.service.EasyCaptchaService;
import com.izouma.nineth.service.sms.SmsService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/sms")
@AllArgsConstructor
public class SmsController {
    private SmsService     smsService;
    private EasyCaptchaService captchaService;

    @GetMapping("/sendVerify")
    public String sendVerify(@RequestParam String phone) {
        if (!Pattern.matches(Constants.Regex.PHONE, phone)) {
            throw new BusinessException("请输入正确的手机号");
        }

        return smsService.sendVerify(phone);
    }

    @GetMapping("/sendCaptchaVerify")
    public String sendCaptchaVerify(@RequestParam String phone, @RequestParam String captcha,   @RequestParam String captchaKey) {
        if (!Pattern.matches(Constants.Regex.PHONE, phone)) {
            throw new BusinessException("请输入正确的手机号");
        }
        boolean verify = captchaService.verify(RedisKeys.captchaServiceRedisKey , captchaKey, captcha,true);
        if (!verify) {
            throw new BusinessException("图形验证码错误");
        }

        return smsService.sendVerify(phone);
    }

    @GetMapping("/verify")
    public String verify(@RequestParam String phone, @RequestParam String code) throws SmsService.SmsVerifyException {
        return smsService.verify(phone, code);
    }
}
