import { NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { authMiddleware } from '@/lib/auth-middleware' import connectDB from '@/lib/mongodb' import { User as UserModel } from '@/models/user' import BillingService from '@/lib/billing-service' // Schema for billing query parameters const BillingQuerySchema = z.object({ serviceType: z.string().optional(), status: z.string().optional(), limit: z.coerce.number().min(1).max(100).default(20), offset: z.coerce.number().min(0).default(0), }) // GET endpoint to fetch user's billing records export async function GET(request: NextRequest) { try { const user = await authMiddleware(request) if (!user) { return NextResponse.json( { success: false, error: { message: 'Authentication required', code: 'UNAUTHORIZED' }, }, { status: 401 } ) } await connectDB() const { searchParams } = new URL(request.url) const queryParams = { serviceType: searchParams.get('serviceType') || undefined, status: searchParams.get('status') || undefined, limit: searchParams.get('limit') || '20', offset: searchParams.get('offset') || '0', } const validatedParams = BillingQuerySchema.parse(queryParams) // Get user data const userData = await UserModel.findOne({ email: user.email }) if (!userData) { return NextResponse.json( { success: false, error: { message: 'User not found', code: 'USER_NOT_FOUND' }, }, { status: 404 } ) } // Fetch billing records const billings = await BillingService.getUserBillings(user.email, user.id, { serviceType: validatedParams.serviceType, status: validatedParams.status, limit: validatedParams.limit, offset: validatedParams.offset, }) // Get billing statistics const stats = await BillingService.getBillingStats(user.email, user.id) return NextResponse.json({ success: true, data: { billings, stats, pagination: { limit: validatedParams.limit, offset: validatedParams.offset, total: billings.length, }, }, }) } catch (error) { console.error('Failed to fetch billing records:', error) if (error instanceof z.ZodError) { return NextResponse.json( { success: false, error: { message: 'Invalid query parameters', code: 'VALIDATION_ERROR', details: error.issues, }, }, { status: 400 } ) } return NextResponse.json( { success: false, error: { message: 'Failed to fetch billing records', code: 'INTERNAL_ERROR' }, }, { status: 500 } ) } }