/**
 * 用户信息更新API
 * 支持更新昵称、头像、手机号、微信号、支付宝、地址等
 */

import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, nickname, avatar, phone, wechat, alipay, address, autoWithdraw, withdrawAccount } = body
    
    if (!userId) {
      return NextResponse.json({ success: false, message: '缺少用户ID' }, { status: 400 })
    }
    
    // 构建更新字段
    const updates: string[] = []
    const values: any[] = []
    
    if (nickname !== undefined) {
      updates.push('nickname = ?')
      values.push(nickname)
    }
    if (avatar !== undefined) {
      updates.push('avatar = ?')
      values.push(avatar)
    }
    if (phone !== undefined) {
      updates.push('phone = ?')
      values.push(phone)
    }
    if (wechat !== undefined) {
      updates.push('wechat = ?')
      values.push(wechat)
    }
    if (alipay !== undefined) {
      updates.push('alipay = ?')
      values.push(alipay)
    }
    if (address !== undefined) {
      updates.push('address = ?')
      values.push(address)
    }
    if (autoWithdraw !== undefined) {
      updates.push('auto_withdraw = ?')
      values.push(autoWithdraw ? 1 : 0)
    }
    if (withdrawAccount !== undefined) {
      updates.push('withdraw_account = ?')
      values.push(withdrawAccount)
    }
    
    // 添加更新时间
    updates.push('updated_at = NOW()')
    
    if (updates.length === 1) {
      return NextResponse.json({ success: false, message: '没有需要更新的字段' }, { status: 400 })
    }
    
    // 执行更新
    values.push(userId)
    const sql = `UPDATE users SET ${updates.join(', ')} WHERE id = ?`
    
    await query(sql, values)
    
    return NextResponse.json({
      success: true,
      message: '更新成功'
    })
    
  } catch (error) {
    console.error('[User Update] Error:', error)
    return NextResponse.json({
      success: false,
      message: '更新失败',
      error: String(error)
    }, { status: 500 })
  }
}
