import * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525'
import Dysmsapi20170525_Module from '@alicloud/dysmsapi20170525'
import * as $OpenApi from '@alicloud/openapi-client'
import * as $Util from '@alicloud/tea-util'

// @ts-ignore
// https://github.com/aliyun/alibabacloud-typescript-sdk/issues/30
const Client = Dysmsapi20170525_Module.default || Dysmsapi20170525_Module

const accessKeyId = process.env.ALIYUN_ACCESS_KEY_ID || ''
const accessKeySecret = process.env.ALIYUN_ACCESS_KEY_SECRET || ''
const signName = process.env.ALIYUN_SMS_SIGN_NAME || ''
const templateCode = process.env.ALIYUN_SMS_TEMPLATE_CODE || ''

let client: any = null

function getClient(): any {
  if (client) return client
  if (!accessKeyId || !accessKeySecret) {
    throw new Error('阿里云短信配置缺失：请设置 ALIYUN_ACCESS_KEY_ID 和 ALIYUN_ACCESS_KEY_SECRET')
  }
  client = new Client(new $OpenApi.Config({
    accessKeyId,
    accessKeySecret,
    endpoint: 'dysmsapi.aliyuncs.com',
  }))
  return client
}

const runtime = new $Util.RuntimeOptions({})

/**
 * 格式化手机号码用于阿里云SMS
 * 阿里云只支持中国大陆手机号，需要移除+86前缀
 */
function formatPhoneForAliyun(phoneNumber: string): string {
  let cleanPhone = phoneNumber.replace(/\D/g, '')
  // 如果是带86前缀的号码，移除86前缀
  if (cleanPhone.startsWith('86') && cleanPhone.length === 13) {
    cleanPhone = cleanPhone.substring(2)
  }
  // 验证是否为有效的中国大陆手机号（11位且以1开头）
  if (cleanPhone.length !== 11 || !cleanPhone.startsWith('1')) {
    throw new Error(`无效的中国大陆手机号: ${phoneNumber}`)
  }
  return cleanPhone
}

export interface SMSResult {
  success: boolean
  messageId?: string
  error?: string
}

/**
 * 使用阿里云发送短信验证码
 */
export async function sendAliyunSMS(phoneNumber: string, code: string): Promise<SMSResult> {
  try {
    const formattedPhone = formatPhoneForAliyun(phoneNumber)

    if (!signName || !templateCode) {
      throw new Error('阿里云短信配置缺失：请设置 ALIYUN_SMS_SIGN_NAME 和 ALIYUN_SMS_TEMPLATE_CODE')
    }

    const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: formattedPhone,
      signName,
      templateCode,
      templateParam: JSON.stringify({ code }),
    })

    const response = await getClient().sendSmsWithOptions(sendSmsRequest, runtime)

    if (!response.body) {
      throw new Error('阿里云短信服务返回空响应')
    }

    if (response.body.code !== 'OK') {
      console.error('阿里云短信发送失败:', response.body)
      return {
        success: false,
        error: response.body.message || '阿里云短信发送失败',
      }
    }

    return {
      success: true,
      messageId: response.body.bizId || undefined,
    }
  } catch (error) {
    console.error('发送阿里云短信失败:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '未知错误',
    }
  }
}
