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

// 获取所有用户
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const id = searchParams.get('id')
    const phone = searchParams.get('phone')

    if (id) {
      const user = await userDB.getById(id)
      return NextResponse.json({ success: true, user })
    }

    if (phone) {
      const user = await userDB.getByPhone(phone)
      return NextResponse.json({ success: true, user })
    }

    const users = await userDB.getAll()
    return NextResponse.json({ success: true, users })
  } catch (error: any) {
    console.error('Get users error:', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message 
    }, { status: 500 })
  }
}

// 创建用户
export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { phone, nickname, password, referral_code, referred_by } = body

    // 检查手机号是否已存在
    const existing = await userDB.getByPhone(phone)
    if (existing) {
      return NextResponse.json({ 
        success: false, 
        error: '该手机号已注册' 
      }, { status: 400 })
    }

    const user = await userDB.create({
      id: `user_${Date.now()}`,
      phone,
      nickname,
      password,
      referral_code: referral_code || `REF${Date.now().toString(36).toUpperCase()}`,
      referred_by
    })

    return NextResponse.json({ success: true, user })
  } catch (error: any) {
    console.error('Create user error:', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message 
    }, { status: 500 })
  }
}

// 更新用户
export async function PUT(req: NextRequest) {
  try {
    const body = await req.json()
    const { id, ...updates } = body

    if (!id) {
      return NextResponse.json({ 
        success: false, 
        error: '缺少用户ID' 
      }, { status: 400 })
    }

    await userDB.update(id, updates)
    const user = await userDB.getById(id)
    
    return NextResponse.json({ success: true, user })
  } catch (error: any) {
    console.error('Update user error:', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message 
    }, { status: 500 })
  }
}

// 删除用户
export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const id = searchParams.get('id')

    if (!id) {
      return NextResponse.json({ 
        success: false, 
        error: '缺少用户ID' 
      }, { status: 400 })
    }

    await userDB.delete(id)
    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error('Delete user error:', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message 
    }, { status: 500 })
  }
}
