// app/api/admin/payment/route.ts
// 付费模块管理API

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

// 模拟订单数据
let orders = [
  {
    id: 'ORDER_001',
    userId: 'user_001',
    userName: '张三',
    amount: 9.9,
    status: 'paid',
    paymentMethod: 'wechat',
    createdAt: new Date('2025-01-10').toISOString(),
    paidAt: new Date('2025-01-10').toISOString()
  },
  {
    id: 'ORDER_002',
    userId: 'user_002',
    userName: '李四',
    amount: 10.9,
    status: 'paid',
    paymentMethod: 'wechat',
    createdAt: new Date('2025-01-11').toISOString(),
    paidAt: new Date('2025-01-11').toISOString()
  }
]

// GET: 获取订单列表
export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url)
  const status = searchParams.get('status')
  const page = parseInt(searchParams.get('page') || '1')
  const pageSize = parseInt(searchParams.get('pageSize') || '20')

  // 过滤订单
  let filteredOrders = orders
  if (status) {
    filteredOrders = orders.filter(order => order.status === status)
  }

  // 分页
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const paginatedOrders = filteredOrders.slice(start, end)

  // 统计数据
  const stats = {
    total: orders.length,
    paid: orders.filter(o => o.status === 'paid').length,
    pending: orders.filter(o => o.status === 'pending').length,
    refunded: orders.filter(o => o.status === 'refunded').length,
    totalRevenue: orders
      .filter(o => o.status === 'paid')
      .reduce((sum, o) => sum + o.amount, 0)
  }

  return NextResponse.json({
    success: true,
    orders: paginatedOrders,
    pagination: {
      page,
      pageSize,
      total: filteredOrders.length,
      totalPages: Math.ceil(filteredOrders.length / pageSize)
    },
    stats
  })
}

// POST: 创建订单（手动）
export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { userId, userName, amount, note } = body

    if (!userId || !amount) {
      return NextResponse.json(
        { error: '用户ID和金额不能为空' },
        { status: 400 }
      )
    }

    const newOrder = {
      id: `ORDER_${Date.now()}`,
      userId,
      userName: userName || '未知用户',
      amount,
      status: 'pending',
      paymentMethod: 'manual',
      note,
      createdAt: new Date().toISOString()
    }

    orders.push(newOrder)

    return NextResponse.json({
      success: true,
      message: '订单创建成功',
      order: newOrder
    })
  } catch (error) {
    return NextResponse.json(
      { error: '创建订单失败' },
      { status: 500 }
    )
  }
}

// PUT: 更新订单状态
export async function PUT(req: NextRequest) {
  try {
    const body = await req.json()
    const { orderId, status, note } = body

    const orderIndex = orders.findIndex(o => o.id === orderId)
    if (orderIndex === -1) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      )
    }

    orders[orderIndex] = {
      ...orders[orderIndex],
      status,
      note: note || orders[orderIndex].note,
      updatedAt: new Date().toISOString()
    }

    if (status === 'paid') {
      orders[orderIndex].paidAt = new Date().toISOString()
    }

    return NextResponse.json({
      success: true,
      message: '订单状态更新成功',
      order: orders[orderIndex]
    })
  } catch (error) {
    return NextResponse.json(
      { error: '更新订单失败' },
      { status: 500 }
    )
  }
}

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

    if (!orderId) {
      return NextResponse.json(
        { error: '订单ID不能为空' },
        { status: 400 }
      )
    }

    const orderIndex = orders.findIndex(o => o.id === orderId)
    if (orderIndex === -1) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      )
    }

    orders.splice(orderIndex, 1)

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