import { NextRequest, NextResponse } from 'next/server'
import { purchaseDB, userDB, distributionDB } 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 purchases = await purchaseDB.getByUserId(userId)
      return NextResponse.json({ success: true, purchases })
    }

    const purchases = await purchaseDB.getAll()
    return NextResponse.json({ success: true, purchases })
  } catch (error: any) {
    console.error('Get purchases 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, 
      type, 
      section_id, 
      section_title, 
      amount, 
      payment_method,
      referral_code 
    } = body

    // 创建购买记录
    const purchase = await purchaseDB.create({
      id: `purchase_${Date.now()}`,
      user_id,
      type,
      section_id,
      section_title,
      amount,
      payment_method,
      referral_code,
      referrer_earnings: 0,
      status: 'completed'
    })

    // 更新用户购买状态
    if (type === 'fullbook') {
      await userDB.update(user_id, { has_full_book: true })
    }

    // 处理分销佣金
    if (referral_code) {
      // 查找推荐人
      const users = await userDB.getAll()
      const referrer = users.find((u: any) => u.referral_code === referral_code)
      
      if (referrer) {
        const commissionRate = 0.9 // 90% 佣金
        const commissionAmount = amount * commissionRate

        // 查找有效的绑定关系
        const binding = await distributionDB.getActiveBindingByReferee(user_id)
        
        if (binding) {
          // 创建佣金记录
          await distributionDB.createCommission({
            id: `commission_${Date.now()}`,
            binding_id: binding.id,
            referrer_id: referrer.id,
            referee_id: user_id,
            order_id: purchase.id,
            amount,
            commission_rate: commissionRate * 100,
            commission_amount: commissionAmount,
            status: 'pending'
          })

          // 更新推荐人收益
          await userDB.update(referrer.id, {
            earnings: (referrer.earnings || 0) + commissionAmount,
            pending_earnings: (referrer.pending_earnings || 0) + commissionAmount
          })

          // 更新购买记录的推荐人收益
          purchase.referrer_earnings = commissionAmount
        }
      }
    }

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