/**
 * 用户资料API
 * 用于完善用户信息（头像、微信号、手机号）
 */

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

/**
 * GET - 获取用户资料
 */
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const userId = searchParams.get('userId')
  const openId = searchParams.get('openId')
  
  if (!userId && !openId) {
    return NextResponse.json({
      success: false,
      error: '请提供userId或openId'
    }, { status: 400 })
  }
  
  try {
    const users = await query(`
      SELECT id, open_id, nickname, avatar, phone, wechat_id, 
             referral_code, has_full_book, is_admin,
             earnings, pending_earnings, referral_count, created_at
      FROM users 
      WHERE ${userId ? 'id = ?' : 'open_id = ?'}
    `, [userId || openId]) as any[]
    
    if (users.length === 0) {
      return NextResponse.json({
        success: false,
        error: '用户不存在'
      }, { status: 404 })
    }
    
    const user = users[0]
    
    // 检查资料完整度
    const profileComplete = !!(user.phone || user.wechat_id)
    const hasAvatar = !!user.avatar && !user.avatar.includes('picsum.photos')
    
    return NextResponse.json({
      success: true,
      data: {
        id: user.id,
        openId: user.open_id,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        wechatId: user.wechat_id,
        referralCode: user.referral_code,
        hasFullBook: user.has_full_book,
        earnings: parseFloat(user.earnings) || 0,
        pendingEarnings: parseFloat(user.pending_earnings) || 0,
        referralCount: user.referral_count || 0,
        profileComplete,
        hasAvatar,
        createdAt: user.created_at
      }
    })
    
  } catch (error) {
    console.error('[UserProfile] GET错误:', error)
    return NextResponse.json({
      success: false,
      error: '获取用户资料失败: ' + (error as Error).message
    }, { status: 500 })
  }
}

/**
 * POST - 更新用户资料
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, openId, nickname, avatar, phone, wechatId } = body
    
    // 确定用户
    const identifier = userId || openId
    const identifierField = userId ? 'id' : 'open_id'
    
    if (!identifier) {
      return NextResponse.json({
        success: false,
        error: '请提供userId或openId'
      }, { status: 400 })
    }
    
    // 检查用户是否存在
    const users = await query(`SELECT id FROM users WHERE ${identifierField} = ?`, [identifier]) as any[]
    if (users.length === 0) {
      return NextResponse.json({
        success: false,
        error: '用户不存在'
      }, { status: 404 })
    }
    
    const realUserId = users[0].id
    
    // 构建更新字段
    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) {
      // 验证手机号格式
      if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
        return NextResponse.json({
          success: false,
          error: '手机号格式不正确'
        }, { status: 400 })
      }
      updates.push('phone = ?')
      values.push(phone)
    }
    if (wechatId !== undefined) {
      updates.push('wechat_id = ?')
      values.push(wechatId)
    }
    
    if (updates.length === 0) {
      return NextResponse.json({
        success: false,
        error: '没有需要更新的字段'
      }, { status: 400 })
    }
    
    // 执行更新
    values.push(realUserId)
    await query(`UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`, values)
    
    // 返回更新后的用户信息
    const updatedUsers = await query(`
      SELECT id, nickname, avatar, phone, wechat_id, referral_code
      FROM users WHERE id = ?
    `, [realUserId]) as any[]
    
    return NextResponse.json({
      success: true,
      message: '资料更新成功',
      data: {
        id: updatedUsers[0].id,
        nickname: updatedUsers[0].nickname,
        avatar: updatedUsers[0].avatar,
        phone: updatedUsers[0].phone,
        wechatId: updatedUsers[0].wechat_id,
        referralCode: updatedUsers[0].referral_code
      }
    })
    
  } catch (error) {
    console.error('[UserProfile] POST错误:', error)
    return NextResponse.json({
      success: false,
      error: '更新用户资料失败: ' + (error as Error).message
    }, { status: 500 })
  }
}
