package com.izouma.nineth.web.mobile.open.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.izouma.nineth.aspect.CipherParam;
import com.izouma.nineth.aspect.RequestCipher;
import com.izouma.nineth.config.Constants;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.service.CustomCaptchaService;
import com.izouma.nineth.service.sms.SmsService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Pattern;

@RestController
@RequestMapping("/sms/v1")
@AllArgsConstructor
public class SmsControllerOpenV1 {
    private SmsService     smsService;
    private final CustomCaptchaService customCaptchaService;

    @PostMapping("/sendVerify")
    @RequestCipher
    public String sendVerify(@CipherParam String encrytorData) {
        JSONObject jsonObject = JSON.parseObject(encrytorData);
        String phone = jsonObject.getString("phone");
        String captchaKey = jsonObject.getString("captchaKey");
        String captcha = jsonObject.getString("captcha");
        if (!Pattern.matches(Constants.Regex.PHONE, phone)) {
            throw new BusinessException("请输入正确的手机号");
        }
        if (!customCaptchaService.verify(captchaKey, captcha, true)) {
            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);
    }
}
