← back to Dear Bubbe Nextjs

app/api/email-stats/route.ts

104 lines

import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

const emailsDir = path.join(process.cwd(), 'data', 'emails')

export async function GET(request: NextRequest) {
  try {
    // Ensure directory exists
    if (!fs.existsSync(emailsDir)) {
      return NextResponse.json({
        success: true,
        stats: {
          totalEmails: 0,
          emailsByType: {},
          emailsByDay: {},
          topRecipients: [],
          recentEmails: []
        }
      })
    }
    
    // Read all email files
    const files = fs.readdirSync(emailsDir).filter(f => f.endsWith('.json'))
    
    let emailsByType: Record<string, number> = {}
    let emailsByDay: Record<string, number> = {}
    let emailsByRecipient: Record<string, number> = {}
    let recentEmails: any[] = []
    let totalSize = 0
    
    for (const file of files) {
      try {
        const filePath = path.join(emailsDir, file)
        const stats = fs.statSync(filePath)
        totalSize += stats.size
        
        const content = fs.readFileSync(filePath, 'utf-8')
        const email = JSON.parse(content)
        
        // Count by type
        emailsByType[email.type] = (emailsByType[email.type] || 0) + 1
        
        // Count by day
        const day = new Date(email.sentAt).toISOString().split('T')[0]
        emailsByDay[day] = (emailsByDay[day] || 0) + 1
        
        // Count by recipient
        emailsByRecipient[email.to] = (emailsByRecipient[email.to] || 0) + 1
        
        // Add to recent emails (without full HTML)
        recentEmails.push({
          id: email.id,
          type: email.type,
          to: email.to,
          subject: email.subject,
          sentAt: email.sentAt,
          htmlSize: email.html?.length || 0
        })
      } catch (error) {
        console.error(`Error processing file ${file}:`, error)
      }
    }
    
    // Sort recent emails by date
    recentEmails.sort((a, b) => 
      new Date(b.sentAt).getTime() - new Date(a.sentAt).getTime()
    )
    
    // Get top recipients
    const topRecipients = Object.entries(emailsByRecipient)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10)
      .map(([email, count]) => ({ email, count }))
    
    // Calculate statistics
    const stats = {
      totalEmails: files.length,
      totalSize: `${(totalSize / 1024).toFixed(2)} KB`,
      emailsByType,
      emailsByDay,
      topRecipients,
      recentEmails: recentEmails.slice(0, 20), // Last 20 emails
      averageEmailSize: files.length > 0 
        ? `${(totalSize / files.length / 1024).toFixed(2)} KB`
        : '0 KB'
    }
    
    return NextResponse.json({
      success: true,
      stats
    })
    
  } catch (error) {
    console.error('[EMAIL-STATS] Error:', error)
    return NextResponse.json(
      { 
        success: false,
        error: 'Failed to retrieve email statistics'
      },
      { status: 500 }
    )
  }
}