// app/api/miniprogram/qrcode/route.ts
// 生成带参数的小程序码 - 绑定推荐人ID

import { NextRequest, NextResponse } from 'next/server'

const APPID = process.env.WECHAT_APPID || 'wxb8bbb2b10dec74aa'
const APPSECRET = process.env.WECHAT_APPSECRET || '25b7e7fdb7998e5107e242ebb6ddabd0'

// 获取access_token
async function getAccessToken() {
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`
  const res = await fetch(url)
  const data = await res.json()
  
  if (data.access_token) {
    return data.access_token
  }
  throw new Error(data.errmsg || '获取access_token失败')
}

export async function POST(req: NextRequest) {
  try {
    const { scene, page, width = 280 } = await req.json()
    
    if (!scene) {
      return NextResponse.json({ error: '缺少scene参数' }, { status: 400 })
    }
    
    // 获取access_token
    const accessToken = await getAccessToken()
    
    // 生成小程序码
    const qrcodeUrl = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`
    
    const qrcodeRes = await fetch(qrcodeUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        scene: scene.slice(0, 32), // 最多32个字符
        page: page || 'pages/index/index',
        width,
        auto_color: false,
        line_color: { r: 0, g: 206, b: 209 },
        is_hyaline: false
      })
    })
    
    // 检查响应类型
    const contentType = qrcodeRes.headers.get('content-type')
    
    if (contentType?.includes('application/json')) {
      // 返回了错误信息
      const errorData = await qrcodeRes.json()
      console.error('[QRCode] 生成失败:', errorData)
      return NextResponse.json({ 
        error: errorData.errmsg || '生成小程序码失败',
        errcode: errorData.errcode 
      }, { status: 500 })
    }
    
    // 返回图片
    const imageBuffer = await qrcodeRes.arrayBuffer()
    const base64 = Buffer.from(imageBuffer).toString('base64')
    
    return NextResponse.json({
      success: true,
      image: `data:image/png;base64,${base64}`
    })
    
  } catch (error) {
    console.error('[QRCode] Error:', error)
    return NextResponse.json(
      { error: '生成小程序码失败' },
      { status: 500 }
    )
  }
}
