import { NextRequest, NextResponse } from 'next/server' import { statsCollectionService } from '@/lib/services/stats-collection-service' /** * GET /api/cron/cleanup-stats * Delete stats snapshots older than 90 days * * This endpoint is designed to be called by a daily cron job. * It should be protected by a secret token in production. * * Example cron schedule: Once per day at 3am * Vercel cron config in vercel.json: * { * "crons": [ * { "path": "/api/cron/cleanup-stats", "schedule": "0 3 * * *" } * ] * } */ export async function GET(request: NextRequest) { // Verify cron secret (for security in production) const cronSecret = process.env.CRON_SECRET const authHeader = request.headers.get('authorization') if (cronSecret && authHeader !== `Bearer ${cronSecret}`) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } try { const startTime = Date.now() const deletedCount = await statsCollectionService.cleanupOldSnapshots() const duration = Date.now() - startTime return NextResponse.json({ success: true, message: `Cleaned up ${deletedCount} old stats snapshots`, deleted: deletedCount, duration: `${duration}ms`, retentionDays: 90, timestamp: new Date().toISOString() }) } catch (error) { console.error('Cron job failed - cleanup-stats:', error) return NextResponse.json( { error: 'Stats cleanup failed', message: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ) } } // Also support POST for flexibility export async function POST(request: NextRequest) { return GET(request) }