import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { getUserBalance } from '@/lib/services/credit'
import { prisma } from '@/lib/prisma'
import { headers } from 'next/headers'

// GET /api/users/credits - 获取用户信用额度概览（向后兼容）
export async function GET(request: NextRequest) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    })
    
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const user = session.user
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId') || user.id

    if (userId !== user.id) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    // 获取当前余额
    const totalBalance = await getUserBalance(userId)

    // 获取活跃和过期的信用记录（为了向后兼容）
    const activeCredits = await prisma.credit.findMany({
      where: {
        userId,
        isActive: true,
        type: { not: 'consumption' },
        OR: [
          { expiresAt: null },
          { expiresAt: { gt: new Date() } }
        ]
      },
      orderBy: { createdAt: 'desc' }
    })

    const expiredCredits = await prisma.credit.findMany({
      where: {
        userId,
        isActive: true,
        type: { not: 'consumption' },
        expiresAt: { lte: new Date() }
      },
      orderBy: { createdAt: 'desc' }
    })

    return NextResponse.json({
      totalBalance,
      activeCredits: activeCredits.map(credit => ({
        id: credit.id,
        amount: credit.amount,
        type: credit.type,
        note: credit.note,
        expiresAt: credit.expiresAt,
        createdAt: credit.createdAt
      })),
      expiredCredits: expiredCredits.map(credit => ({
        id: credit.id,
        amount: credit.amount,
        type: credit.type,
        note: credit.note,
        expiresAt: credit.expiresAt,
        createdAt: credit.createdAt
      }))
    })

  } catch (error) {
    console.error('Error fetching user credits:', error)
    return NextResponse.json(
      { error: 'Failed to fetch user credits' },
      { status: 500 }
    )
  }
}