import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(request: NextRequest): Promise<NextResponse> {
  const cronSecret = request.headers.get('x-cron-secret')

  if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    // Read retention period from system settings (default: 365 days)
    const retentionSetting = await prisma.systemSettings.findUnique({
      where: { key: 'audit_retention_days' },
    })

    const retentionDays = retentionSetting
      ? parseInt(retentionSetting.value, 10) || 365
      : 365

    const cutoffDate = new Date()
    cutoffDate.setDate(cutoffDate.getDate() - retentionDays)

    // Delete audit log entries older than the retention period
    const result = await prisma.auditLog.deleteMany({
      where: {
        timestamp: {
          lt: cutoffDate,
        },
      },
    })

    return NextResponse.json({
      ok: true,
      cleanedUp: result.count,
      retentionDays,
      cutoffDate: cutoffDate.toISOString(),
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Cron audit cleanup failed:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
