import { NextRequest, NextResponse } from 'next/server'
import { getUserCreditSummary, checkAndRefreshProMonthlyCredit } from '@/lib/credits'

// GET /api/users/credits - 获取用户信用额度概览
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 401 })
    }

    // 检查Pro用户是否需要刷新月度额度
    await checkAndRefreshProMonthlyCredit(userId)

    // 获取信用额度概览
    const creditSummary = await getUserCreditSummary(userId)

    return NextResponse.json(creditSummary)

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