package com.izouma.nineth.web;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.dto.CaptchaDTO;
import com.izouma.nineth.enums.CaptchaType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.service.CustomCaptchaService;
import com.izouma.nineth.service.EasyCaptchaService;
import com.izouma.nineth.service.SysConfigService;
import com.izouma.nineth.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/captcha")
@AllArgsConstructor
public class CaptchaController {

    private final EasyCaptchaService easyCaptchaService;
    private final CustomCaptchaService customCaptchaService;

    private final SysConfigService sysConfigService;

    @PostMapping("/get")
    public Result get(@RequestParam int code){
        try {
            return easyCaptchaService.gen(RedisKeys.captchaServiceRedisKey , code, sysConfigService.getInt(SysConstants.GRAPH_AUTHCODE_EXPIRATION_TIME));
        }catch (Exception e){
            throw new BusinessException("获取验证码失败");
        }

    }

    @PostMapping("/verify")
    public boolean verify( @RequestParam String key, @RequestParam String code) {
        return easyCaptchaService.verify(RedisKeys.captchaServiceRedisKey , key ,code,false);
    }


    /**
     * 自定义的计算验证码
     * @return
     * @throws Exception
     */
    @PostMapping("/getCustom")
    public CaptchaDTO getCustom() throws  Exception{
        CaptchaDTO captchaDTO = customCaptchaService.gen(CaptchaType.ARITHMETIC, 2);
        return captchaDTO;
    }

    /**
     * 自定义的计算验证码
     * @return
     * @throws Exception
     */
    @PostMapping("/verifyCustom")
    public boolean verifyCustom(@RequestParam String key, @RequestParam String code) throws  Exception{
        boolean res = customCaptchaService.verify(key, code, true);
        return res;
    }



}
