package com.storlead.sms.api;

import cn.hutool.core.util.StrUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.sms.spi.SmsCaptchaScene;
import com.storlead.sms.spi.SmsCaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 短信验证码 HTTP（依赖 {@link SmsCaptchaService} 契约，与实现解耦）
 */
@Api(tags = "短信: 验证码")
@RestController
@RequestMapping("/sys/sms/captcha")
public class SmsCaptchaApiController {

    @Resource
    private SmsCaptchaService smsCaptchaService;

    @ApiOperation("发送验证码")
    @PostMapping("/send")
    public Result<?> send(
            @ApiParam(value = "手机号", required = true) @RequestParam String mobile,
            @ApiParam(value = "场景，默认 LOGIN", allowableValues = "LOGIN") @RequestParam(defaultValue = "LOGIN") String scene) {
        if (StrUtil.isBlank(mobile)) {
            return Result.error("参数错误");
        }
        SmsCaptchaScene s = parseScene(scene);
        if (s == null) {
            return Result.error("不支持的场景: " + scene);
        }
        return Result.result(smsCaptchaService.sendCaptcha(mobile, s));
    }

    @ApiOperation("校验验证码")
    @PostMapping("/verify")
    public Result<?> verify(
            @ApiParam(value = "手机号", required = true) @RequestParam String mobile,
            @ApiParam(value = "验证码", required = true) @RequestParam String code,
            @ApiParam(value = "场景，默认 LOGIN", allowableValues = "LOGIN") @RequestParam(defaultValue = "LOGIN") String scene,
            @ApiParam(value = "校验成功后是否删除缓存（一次性）", defaultValue = "true") @RequestParam(defaultValue = "true") boolean consume) {
        if (StrUtil.isBlank(mobile) || StrUtil.isBlank(code)) {
            return Result.error("参数错误");
        }
        SmsCaptchaScene s = parseScene(scene);
        if (s == null) {
            return Result.error("不支持的场景: " + scene);
        }
        return Result.result(smsCaptchaService.verifyCaptcha(mobile, code, s, consume));
    }

    private static SmsCaptchaScene parseScene(String scene) {
        if (StrUtil.isBlank(scene)) {
            return SmsCaptchaScene.LOGIN;
        }
        try {
            return SmsCaptchaScene.valueOf(scene.trim().toUpperCase());
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
}
