import { NextRequest, NextResponse } from 'next/server' import { auth } from '@/lib/auth' import { prisma } from '@/lib/prisma' import { UserStatus } from '@prisma/client' /** * GET /api/v1/admin/customers/[id] * Get customer details with orders and subscriptions */ export async function GET( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth() if (!session || session.user.userType !== 'staff') { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { id: customerId } = await params const customer = await prisma.user.findUnique({ where: { id: customerId }, include: { subscriptions: { orderBy: { createdAt: 'desc' }, }, orders: { orderBy: { createdAt: 'desc' }, include: { _count: { select: { provisioningLogs: true }, }, }, }, tokenUsage: { orderBy: { createdAt: 'desc' }, take: 100, }, _count: { select: { orders: true, subscriptions: true, tokenUsage: true, }, }, }, }) if (!customer) { return NextResponse.json({ error: 'Customer not found' }, { status: 404 }) } // Calculate total token usage const totalTokensUsed = customer.tokenUsage.reduce( (acc, usage) => acc + usage.tokensInput + usage.tokensOutput, 0 ) // Get current subscription's token limit const currentSubscription = customer.subscriptions[0] const tokenLimit = currentSubscription?.tokenLimit || 0 return NextResponse.json({ ...customer, totalTokensUsed, tokenLimit, }) } catch (error) { console.error('Error getting customer:', error) return NextResponse.json( { error: 'Failed to get customer' }, { status: 500 } ) } } /** * PATCH /api/v1/admin/customers/[id] * Update customer details */ export async function PATCH( request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { try { const session = await auth() if (!session || session.user.userType !== 'staff') { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { id: customerId } = await params const body = await request.json() // Validate customer exists const existingCustomer = await prisma.user.findUnique({ where: { id: customerId }, }) if (!existingCustomer) { return NextResponse.json({ error: 'Customer not found' }, { status: 404 }) } // Build update data const updateData: { name?: string company?: string status?: UserStatus } = {} if (body.name !== undefined) { updateData.name = body.name } if (body.company !== undefined) { updateData.company = body.company } if (body.status !== undefined) { updateData.status = body.status as UserStatus } const customer = await prisma.user.update({ where: { id: customerId }, data: updateData, include: { subscriptions: { orderBy: { createdAt: 'desc' }, take: 1, }, _count: { select: { orders: true, subscriptions: true, }, }, }, }) return NextResponse.json(customer) } catch (error) { console.error('Error updating customer:', error) return NextResponse.json( { error: 'Failed to update customer' }, { status: 500 } ) } }