package com.storlead.login;

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;

/**
 * 登录域验证码入口：仅依赖 {@link SmsCaptchaService}（SPI），与短信实现解耦。
 */
@RestController
@RequestMapping("/sys/auth/captcha")
@Api(tags = "平台中心 - 系统: 验证码")
public class AuthCaptchaApiController {

    @Resource
    private SmsCaptchaService smsCaptchaService;

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