import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' export async function GET(req: NextRequest) { const session = await getServerSession(authOptions) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const { searchParams } = new URL(req.url) const clientId = searchParams.get('clientId') const from = searchParams.get('from') const to = searchParams.get('to') const format = searchParams.get('format') const where: any = {} if (clientId) where.clientId = clientId if (from || to) { where.sentAt = {} if (from) where.sentAt.gte = new Date(from) if (to) where.sentAt.lte = new Date(to + 'T23:59:59Z') } const logs = await prisma.smsLog.findMany({ where, include: { client: { select: { name: true } }, queue: true }, orderBy: { sentAt: 'desc' }, take: format === 'csv' ? 10000 : 500, }) if (format === 'csv') { const headers = ['Date', 'Client', 'Student Name', 'Student ID', 'Phone', 'Event', 'Status', 'Error'] const rows = logs.map(l => [ new Date(l.sentAt).toISOString(), l.client.name, l.queue.studentName, l.queue.studentId, l.phone, l.queue.event, l.status, l.errorReason || '', ]) const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n') return new NextResponse(csv, { headers: { 'Content-Type': 'text/csv', 'Content-Disposition': `attachment; filename="sms-report-${Date.now()}.csv"`, }, }) } // Stats summary const stats = { total: logs.length, success: logs.filter(l => l.status === 'SUCCESS').length, failed: logs.filter(l => l.status === 'FAILED').length, logs, } return NextResponse.json(stats) }