import { Injectable, Logger } from '@nestjs/common';
import { SmsVerificationType } from '../../domain/entities/sms-verification.entity';
import { ISmsProvider, SmsDeliveryResult } from './sms-provider.interface';

/**
 * 阿里云 SMS Provider
 *
 * 使用阿里云短信服务 (dysmsapi) 发送验证码。
 * 需要安装: npm install @alicloud/dysmsapi20170525 @alicloud/openapi-client
 *
 * 环境变量:
 * - ALIYUN_ACCESS_KEY_ID
 * - ALIYUN_ACCESS_KEY_SECRET
 * - ALIYUN_SMS_SIGN_NAME (签名名称)
 * - ALIYUN_SMS_TEMPLATE_CODE (模板代码)
 * - ALIYUN_SMS_ENDPOINT (默认 dysmsapi.aliyuncs.com)
 */
@Injectable()
export class AliyunSmsProvider implements ISmsProvider {
  private readonly logger = new Logger('AliyunSmsProvider');
  private client: any; // Dysmsapi20170525 client (lazy init)

  async send(
    phone: string,
    code: string,
    type: SmsVerificationType,
  ): Promise<SmsDeliveryResult> {
    try {
      const client = await this.getClient();

      // 去掉 +86 前缀 (阿里云要求纯数字)
      const phoneNumber = phone.startsWith('+86') ? phone.slice(3) : phone;

      const templateParam = JSON.stringify({ code });
      const signName = process.env.ALIYUN_SMS_SIGN_NAME || '券金融';
      const templateCode = this.getTemplateCode(type);

      const result = await client.sendSms({
        phoneNumbers: phoneNumber,
        signName,
        templateCode,
        templateParam,
      });

      if (result.body?.code === 'OK') {
        return {
          success: true,
          providerId: result.body.bizId,
        };
      }

      this.logger.error(
        `Aliyun SMS failed: ${result.body?.code} - ${result.body?.message}`,
      );
      return {
        success: false,
        errorMsg: `${result.body?.code}: ${result.body?.message}`,
      };
    } catch (error: any) {
      this.logger.error(`Aliyun SMS error: ${error.message}`);
      return { success: false, errorMsg: error.message };
    }
  }

  private getTemplateCode(type: SmsVerificationType): string {
    // 可为不同类型配置不同模板，默认使用通用模板
    return process.env.ALIYUN_SMS_TEMPLATE_CODE || '';
  }

  private async getClient() {
    if (this.client) return this.client;

    // 动态 require (仅 SMS_ENABLED=true 时调用, 开发环境不安装这些包)
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525').default;
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const { Config } = require('@alicloud/openapi-client');

    const config = new Config({
      accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
      endpoint: process.env.ALIYUN_SMS_ENDPOINT || 'dysmsapi.aliyuncs.com',
    });

    this.client = new Dysmsapi20170525(config);
    return this.client;
  }
}
