import { NextRequest, NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase-server'
import { getCreditTransactions } from '@/lib/services/credit'

export async function GET(request: NextRequest) {
  try {
    const supabase = await createServerSupabaseClient()
    const { data: { user }, error: authError } = await supabase.auth.getUser()

    if (authError || !user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const { searchParams } = new URL(request.url)
    
    // Parse query parameters
    const page = parseInt(searchParams.get('page') || '1', 10)
    const limit = parseInt(searchParams.get('limit') || '20', 10)
    const type = searchParams.get('type') || undefined
    const category = searchParams.get('category') || undefined
    const sortBy = (searchParams.get('sortBy') || 'createdAt') as 'createdAt' | 'amount' | 'balance'
    const sortOrder = (searchParams.get('sortOrder') || 'desc') as 'asc' | 'desc'
    
    // Parse date filters if provided
    const startDateParam = searchParams.get('startDate')
    const endDateParam = searchParams.get('endDate')
    const startDate = startDateParam ? new Date(startDateParam) : undefined
    const endDate = endDateParam ? new Date(endDateParam) : undefined

    const result = await getCreditTransactions({
      userId: user.id,
      page,
      limit: Math.min(limit, 100), // Cap at 100 to prevent excessive load
      type,
      category,
      sortBy,
      sortOrder,
      startDate,
      endDate
    })

    return NextResponse.json(result)
  } catch (error) {
    console.error('Error fetching credit transactions:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}