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

// 获取分销数据
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const type = searchParams.get('type')
    const referrerId = searchParams.get('referrer_id')

    // 获取佣金记录
    if (type === 'commissions') {
      const commissions = await distributionDB.getAllCommissions()
      return NextResponse.json({ success: true, commissions })
    }

    // 获取指定推荐人的绑定
    if (referrerId) {
      const bindings = await distributionDB.getBindingsByReferrer(referrerId)
      return NextResponse.json({ success: true, bindings })
    }

    // 获取所有绑定关系
    const bindings = await distributionDB.getAllBindings()
    return NextResponse.json({ success: true, bindings })
  } catch (error: any) {
    console.error('Get distribution data 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 { type, data } = body

    if (type === 'binding') {
      const binding = await distributionDB.createBinding({
        id: `binding_${Date.now()}`,
        ...data,
        bound_at: new Date().toISOString(),
        expires_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天有效期
        status: 'active'
      })
      return NextResponse.json({ success: true, binding })
    }

    if (type === 'commission') {
      const commission = await distributionDB.createCommission({
        id: `commission_${Date.now()}`,
        ...data,
        status: 'pending'
      })
      return NextResponse.json({ success: true, commission })
    }

    return NextResponse.json({ 
      success: false, 
      error: '未知操作类型' 
    }, { status: 400 })
  } catch (error: any) {
    console.error('Create distribution record 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 distributionDB.updateBindingStatus(id, status)
    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error('Update distribution status error:', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message 
    }, { status: 500 })
  }
}
