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

// 获取提现记录
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const userId = searchParams.get('user_id')

    if (userId) {
      const withdrawals = await withdrawalDB.getByUserId(userId)
      return NextResponse.json({ success: true, withdrawals })
    }

    const withdrawals = await withdrawalDB.getAll()
    return NextResponse.json({ success: true, withdrawals })
  } catch (error: any) {
    console.error('Get withdrawals 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 { user_id, amount, method, account, name } = body

    // 验证用户余额
    const user = await userDB.getById(user_id)
    if (!user) {
      return NextResponse.json({ 
        success: false, 
        error: '用户不存在' 
      }, { status: 404 })
    }

    if ((user.earnings || 0) < amount) {
      return NextResponse.json({ 
        success: false, 
        error: '余额不足' 
      }, { status: 400 })
    }

    // 创建提现记录
    const withdrawal = await withdrawalDB.create({
      id: `withdrawal_${Date.now()}`,
      user_id,
      amount,
      method,
      account,
      name,
      status: 'pending'
    })

    // 扣除用户余额，增加待提现金额
    await userDB.update(user_id, {
      earnings: (user.earnings || 0) - amount,
      pending_earnings: (user.pending_earnings || 0) + amount
    })

    return NextResponse.json({ success: true, withdrawal })
  } catch (error: any) {
    console.error('Create withdrawal 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, status } = body

    if (!id) {
      return NextResponse.json({ 
        success: false, 
        error: '缺少提现记录ID' 
      }, { status: 400 })
    }

    await withdrawalDB.updateStatus(id, status)

    // 如果状态是已完成，更新用户的已提现金额
    if (status === 'completed') {
      const withdrawals = await withdrawalDB.getAll()
      const withdrawal = withdrawals.find((w: any) => w.id === id)
      if (withdrawal) {
        const user = await userDB.getById(withdrawal.user_id)
        if (user) {
          await userDB.update(user.id, {
            pending_earnings: (user.pending_earnings || 0) - withdrawal.amount,
            withdrawn_earnings: (user.withdrawn_earnings || 0) + withdrawal.amount
          })
        }
      }
    }

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