package sms

import (
	"fmt"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	"github.com/alibabacloud-go/tea/tea"
)

// Config 阿里云短信配置
type Config struct {
	AccessKeyID     string
	AccessKeySecret string
	SignName        string
	TemplateCode    string
}

// Client 阿里云短信客户端
type Client struct {
	client   *dysmsapi.Client
	signName string
	template string
}

// NewClient 创建阿里云短信客户端
func NewClient(cfg Config) (*Client, error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(cfg.AccessKeyID),
		AccessKeySecret: tea.String(cfg.AccessKeySecret),
		Endpoint:        tea.String("dysmsapi.aliyuncs.com"),
	}

	client, err := dysmsapi.NewClient(config)
	if err != nil {
		return nil, fmt.Errorf("创建阿里云短信客户端失败: %w", err)
	}

	return &Client{
		client:   client,
		signName: cfg.SignName,
		template: cfg.TemplateCode,
	}, nil
}

// SendCode 发送验证码短信
// mobile: 手机号
// code: 验证码
func (c *Client) SendCode(mobile, code string) error {
	// 模板参数：{"code":"123456"}
	templateParam := fmt.Sprintf(`{"code":"%s"}`, code)

	req := &dysmsapi.SendSmsRequest{
		PhoneNumbers:  tea.String(mobile),
		SignName:      tea.String(c.signName),
		TemplateCode:  tea.String(c.template),
		TemplateParam: tea.String(templateParam),
	}

	resp, err := c.client.SendSms(req)
	if err != nil {
		return fmt.Errorf("发送短信失败: %w", err)
	}

	// 检查返回码
	if resp.Body == nil {
		return fmt.Errorf("发送短信失败: 响应为空")
	}

	if *resp.Body.Code != "OK" {
		return fmt.Errorf("发送短信失败: %s - %s", *resp.Body.Code, *resp.Body.Message)
	}

	return nil
}
