import { Injectable, Logger } from '@nestjs/common'
import axios from 'axios'

const WX_APPID = process.env.WX_APPID
const WX_SECRET = process.env.WX_SECRET

@Injectable()
export class WechatTokenService {
  private readonly logger = new Logger(WechatTokenService.name)
  private accessToken: string = ''
  private expiresAt: number = 0

  async getAccessToken(): Promise<string> {
    if (this.accessToken && Date.now() < this.expiresAt) return this.accessToken
    return this.refreshToken()
  }

  async refreshToken(): Promise<string> {
    if (!WX_APPID || !WX_SECRET) {
      this.logger.warn('微信配置不完整，无法获取 access_token')
      return ''
    }
    try {
      const res = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
        params: { grant_type: 'client_credential', appid: WX_APPID, secret: WX_SECRET },
      })
      this.accessToken = res.data.access_token
      this.expiresAt = Date.now() + (res.data.expires_in - 300) * 1000
      this.logger.log(`微信 access_token 刷新成功，有效期 ${res.data.expires_in}s`)
      return this.accessToken
    } catch (e: any) {
      this.logger.error(`获取微信 access_token 失败: ${e.response?.data || e.message}`)
      return this.accessToken || ''
    }
  }

  /** 发送订阅消息 */
  async sendSubscribeMessage(openid: string, templateId: string, data: Record<string, { value: string }>, pagePath?: string) {
    const token = await this.getAccessToken()
    if (!token) { this.logger.warn('无有效 access_token，跳过消息推送'); return false }
    try {
      await axios.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${token}`, {
        touser: openid,
        template_id: templateId,
        data,
        page: pagePath || 'pages/index/index',
        miniprogram_state: 'formal',
      })
      return true
    } catch (e: any) {
      this.logger.error(`发送订阅消息失败: ${e.response?.data || e.message}`)
      return false
    }
  }
}
