import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $OpenApi from '@alicloud/openapi-client';
import * as $Util from '@alicloud/tea-util';

export interface SmsSendResult {
  success: boolean;
  requestId?: string;
  bizId?: string;
  code?: string;
  message?: string;
}

@Injectable()
export class SmsService implements OnModuleInit {
  private readonly logger = new Logger(SmsService.name);
  private client: Dysmsapi20170525 | null = null;
  private readonly signName: string;
  private readonly templateCode: string;
  private readonly enabled: boolean;

  constructor(private readonly configService: ConfigService) {
    this.signName = this.configService.get('ALIYUN_SMS_SIGN_NAME', '');
    this.templateCode = this.configService.get('ALIYUN_SMS_TEMPLATE_CODE', '');
    this.enabled = this.configService.get('SMS_ENABLED') === 'true';
  }

  async onModuleInit() {
    const accessKeyId = this.configService.get<string>('ALIYUN_ACCESS_KEY_ID');
    const accessKeySecret = this.configService.get<string>('ALIYUN_ACCESS_KEY_SECRET');

    if (!accessKeyId || !accessKeySecret) {
      this.logger.warn('阿里云 SMS 配置缺失，短信功能将使用模拟模式');
      return;
    }

    try {
      const config = new $OpenApi.Config({
        accessKeyId,
        accessKeySecret,
        endpoint: 'dysmsapi.aliyuncs.com',
      });
      this.client = new Dysmsapi20170525(config);
      this.logger.log('阿里云 SMS 客户端初始化成功');
    } catch (error) {
      this.logger.error('阿里云 SMS 客户端初始化失败', error);
    }
  }

  async sendVerificationCode(phoneNumber: string, code: string): Promise<SmsSendResult> {
    const normalized = this.normalizePhone(phoneNumber);
    this.logger.log(`[SMS] 发送验证码到 ${this.maskPhone(normalized)}`);

    if (!this.enabled || !this.client) {
      this.logger.warn(`[SMS] 模拟模式: 验证码 ${code} → ${this.maskPhone(normalized)}`);
      return { success: true, code: 'OK', message: '模拟发送成功' };
    }

    try {
      const req = new $Dysmsapi20170525.SendSmsRequest({
        phoneNumbers: normalized,
        signName: this.signName,
        templateCode: this.templateCode,
        templateParam: JSON.stringify({ code }),
      });
      const runtime = new $Util.RuntimeOptions({ connectTimeout: 15000, readTimeout: 15000 });
      const resp = await this.client.sendSmsWithOptions(req, runtime);
      const body = resp.body;
      const result: SmsSendResult = {
        success: body?.code === 'OK',
        requestId: body?.requestId,
        bizId: body?.bizId,
        code: body?.code,
        message: body?.message,
      };
      if (result.success) {
        this.logger.log(`[SMS] 发送成功: requestId=${result.requestId}`);
      } else {
        this.logger.error(`[SMS] 发送失败: code=${result.code}, msg=${result.message}`);
      }
      return result;
    } catch (error: any) {
      this.logger.error(`[SMS] 发送异常: ${error.message}`);
      return { success: false, code: error.code || 'UNKNOWN_ERROR', message: error.message };
    }
  }

  private normalizePhone(phone: string): string {
    let p = phone.trim();
    if (p.startsWith('+86')) p = p.slice(3);
    else if (p.startsWith('86') && p.length === 13) p = p.slice(2);
    return p;
  }

  private maskPhone(phone: string): string {
    if (phone.length < 7) return phone;
    return phone.slice(0, 3) + '****' + phone.slice(-4);
  }
}
