package captcha

import (
	"os"

	"qnc-server/common/xerr"

	captcha20230305 "github.com/alibabacloud-go/captcha-20230305/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/pkg/errors"
)

// Config 阿里云验证码配置
type Config struct {
	AccessKeyID     string
	AccessKeySecret string
	EndpointURL     string
	SceneID         string
}

// Verify 验证滑块验证码
func Verify(cfg Config, captchaVerifyParam string) error {
	// 开发环境跳过验证
	if os.Getenv("ENV") == "development" {
		return nil
	}

	if captchaVerifyParam == "" {
		return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "empty captchaVerifyParam")
	}

	// 创建阿里云验证码客户端
	clientCfg := &openapi.Config{
		AccessKeyId:     tea.String(cfg.AccessKeyID),
		AccessKeySecret: tea.String(cfg.AccessKeySecret),
	}
	clientCfg.Endpoint = tea.String(cfg.EndpointURL)

	client, err := captcha20230305.NewClient(clientCfg)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建验证码客户端失败: %v", err)
	}

	// 构建验证请求
	req := &captcha20230305.VerifyIntelligentCaptchaRequest{
		SceneId:            tea.String(cfg.SceneID),
		CaptchaVerifyParam: tea.String(captchaVerifyParam),
	}

	// 调用验证接口
	resp, err := client.VerifyIntelligentCaptcha(req)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "验证码校验请求失败: %v", err)
	}

	// 检查验证结果
	if resp == nil || resp.Body == nil || resp.Body.Result == nil {
		return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "响应数据为空")
	}

	if !tea.BoolValue(resp.Body.Result.VerifyResult) {
		return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "验证未通过")
	}

	return nil
}
