const Dypnsapi20170525 = require('@alicloud/dypnsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');

class SmsClient {
  static createClient() {
    let config = new OpenApi.Config({
      accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
    });
    config.endpoint = `dypnsapi.aliyuncs.com`;
    return new Dypnsapi20170525.default(config);
  }

  static async sendVerifyCode(phoneNumber, code) {
    let client = this.createClient();
    let sendSmsVerifyCodeRequest = new Dypnsapi20170525.SendSmsVerifyCodeRequest({
      signName: process.env.SMS_SIGN_NAME,
      templateCode: process.env.SMS_TEMPLATE_CODE,
      phoneNumber: phoneNumber,
      templateParam: `{"code":"${code}","min":"5"}`,
    });
    let runtime = new Util.RuntimeOptions({});
    try {
      return await client.sendSmsVerifyCodeWithOptions(sendSmsVerifyCodeRequest, runtime);
    } catch (error) {
      console.error('短信发送失败:', error.message);
      throw error;
    }
  }
}

module.exports = SmsClient;
