package captcha

import (
	"fmt"
	"os"

	"xingfucha-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-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/pkg/errors"
)

// Config 验证码配置
type Config struct {
	AccessKeyID     string
	AccessKeySecret string
	EndpointURL     string
	SceneID         string
	EKey            string // 加密模式用的 ekey
}

// 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),
		Endpoint:        tea.String(cfg.EndpointURL),
	}
	client, err := captcha20230305.NewClient(clientCfg)
	if err != nil {
		// 阿里云服务异常时,记录日志但视为通过,不影响业务可用性
		fmt.Printf("captcha.NewClient error: %+v\n", err)
		return nil
	}

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

	// 调用验证接口
	runtime := &service.RuntimeOptions{}
	resp, err := client.VerifyIntelligentCaptchaWithOptions(req, runtime)
	if err != nil {
		// 阿里云服务异常时,记录日志但视为通过,不影响业务可用性
		fmt.Printf("captcha.VerifyIntelligentCaptchaWithOptions error: %+v\n", err)
		return nil
	}

	if resp == nil || resp.Body == nil || resp.Body.Result == nil {
		// 阿里云服务异常时,记录日志但视为通过,不影响业务可用性
		fmt.Printf("captcha response is nil or Body is nil or Result is nil\n")
		return nil
	}

	// 检查验证结果
	if tea.BoolValue(resp.Body.Result.VerifyResult) {
		return nil
	}

	// 验证失败
	return errors.Wrapf(xerr.NewErrMsg("图形验证码校验失败"), "captcha verify failed")
}
