// app/api/admin/referral/route.ts
// 分销模块管理API

import { NextRequest, NextResponse } from 'next/server'

// 模拟分销数据
let referralRecords = [
  {
    id: 'REF_001',
    referrerId: 'user_001',
    referrerName: '张三',
    inviteCode: 'ABC123',
    totalReferrals: 5,
    totalOrders: 3,
    totalCommission: 267.00,
    paidCommission: 200.00,
    pendingCommission: 67.00,
    commissionRate: 0.9,
    status: 'active',
    createdAt: new Date('2025-01-01').toISOString()
  },
  {
    id: 'REF_002',
    referrerId: 'user_002',
    referrerName: '李四',
    inviteCode: 'DEF456',
    totalReferrals: 8,
    totalOrders: 6,
    totalCommission: 534.00,
    paidCommission: 400.00,
    pendingCommission: 134.00,
    commissionRate: 0.9,
    status: 'active',
    createdAt: new Date('2025-01-03').toISOString()
  }
]

let commissionRecords = [
  {
    id: 'COMM_001',
    referrerId: 'user_001',
    referrerName: '张三',
    orderId: 'ORDER_001',
    orderAmount: 9.9,
    commissionAmount: 8.91,
    commissionRate: 0.9,
    status: 'paid',
    createdAt: new Date('2025-01-10').toISOString(),
    paidAt: new Date('2025-01-12').toISOString()
  }
]

// GET: 获取分销概览或列表
export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url)
  const type = searchParams.get('type') || 'list'
  const page = parseInt(searchParams.get('page') || '1')
  const pageSize = parseInt(searchParams.get('pageSize') || '20')

  if (type === 'overview') {
    // 返回概览数据
    const overview = {
      totalReferrers: referralRecords.length,
      activeReferrers: referralRecords.filter(r => r.status === 'active').length,
      totalReferrals: referralRecords.reduce((sum, r) => sum + r.totalReferrals, 0),
      totalOrders: referralRecords.reduce((sum, r) => sum + r.totalOrders, 0),
      totalCommission: referralRecords.reduce((sum, r) => sum + r.totalCommission, 0),
      paidCommission: referralRecords.reduce((sum, r) => sum + r.paidCommission, 0),
      pendingCommission: referralRecords.reduce((sum, r) => sum + r.pendingCommission, 0),
      averageCommission: referralRecords.reduce((sum, r) => sum + r.totalCommission, 0) / referralRecords.length
    }

    return NextResponse.json({
      success: true,
      overview
    })
  }

  // 返回列表数据
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const paginatedRecords = referralRecords.slice(start, end)

  return NextResponse.json({
    success: true,
    records: paginatedRecords,
    pagination: {
      page,
      pageSize,
      total: referralRecords.length,
      totalPages: Math.ceil(referralRecords.length / pageSize)
    }
  })
}

// POST: 创建分销记录或处理佣金
export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { action, data } = body

    if (action === 'create_referrer') {
      // 创建推广者
      const { userId, userName, commissionRate } = data

      const newReferrer = {
        id: `REF_${Date.now()}`,
        referrerId: userId,
        referrerName: userName,
        inviteCode: generateInviteCode(),
        totalReferrals: 0,
        totalOrders: 0,
        totalCommission: 0,
        paidCommission: 0,
        pendingCommission: 0,
        commissionRate: commissionRate || 0.9,
        status: 'active',
        createdAt: new Date().toISOString()
      }

      referralRecords.push(newReferrer)

      return NextResponse.json({
        success: true,
        message: '推广者创建成功',
        referrer: newReferrer
      })
    }

    if (action === 'pay_commission') {
      // 支付佣金
      const { referrerId, amount, note } = data

      const referrer = referralRecords.find(r => r.referrerId === referrerId)
      if (!referrer) {
        return NextResponse.json(
          { error: '推广者不存在' },
          { status: 404 }
        )
      }

      if (amount > referrer.pendingCommission) {
        return NextResponse.json(
          { error: '支付金额超过待支付佣金' },
          { status: 400 }
        )
      }

      referrer.paidCommission += amount
      referrer.pendingCommission -= amount

      return NextResponse.json({
        success: true,
        message: '佣金支付成功',
        referrer
      })
    }

    return NextResponse.json(
      { error: '未知操作' },
      { status: 400 }
    )
  } catch (error) {
    return NextResponse.json(
      { error: '操作失败' },
      { status: 500 }
    )
  }
}

// PUT: 更新分销记录
export async function PUT(req: NextRequest) {
  try {
    const body = await req.json()
    const { referrerId, status, commissionRate, note } = body

    const referrerIndex = referralRecords.findIndex(r => r.referrerId === referrerId)
    if (referrerIndex === -1) {
      return NextResponse.json(
        { error: '推广者不存在' },
        { status: 404 }
      )
    }

    referralRecords[referrerIndex] = {
      ...referralRecords[referrerIndex],
      status: status || referralRecords[referrerIndex].status,
      commissionRate: commissionRate !== undefined ? commissionRate : referralRecords[referrerIndex].commissionRate,
      note: note || referralRecords[referrerIndex].note,
      updatedAt: new Date().toISOString()
    }

    return NextResponse.json({
      success: true,
      message: '推广者信息更新成功',
      referrer: referralRecords[referrerIndex]
    })
  } catch (error) {
    return NextResponse.json(
      { error: '更新失败' },
      { status: 500 }
    )
  }
}

// DELETE: 删除分销记录
export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const referrerId = searchParams.get('id')

    if (!referrerId) {
      return NextResponse.json(
        { error: '推广者ID不能为空' },
        { status: 400 }
      )
    }

    const referrerIndex = referralRecords.findIndex(r => r.referrerId === referrerId)
    if (referrerIndex === -1) {
      return NextResponse.json(
        { error: '推广者不存在' },
        { status: 404 }
      )
    }

    referralRecords.splice(referrerIndex, 1)

    return NextResponse.json({
      success: true,
      message: '推广者删除成功'
    })
  } catch (error) {
    return NextResponse.json(
      { error: '删除失败' },
      { status: 500 }
    )
  }
}

// 生成邀请码
function generateInviteCode(): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let code = ''
  for (let i = 0; i < 6; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return code
}
