import { prisma } from '@/lib/prisma'

export const runtime = 'nodejs'

const CUTOFF_DAYS = 7

export async function POST(request: Request) {
  const auth = request.headers.get('authorization')
  const expected = process.env.CRON_SECRET
  if (!expected || auth !== `Bearer ${expected}`) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const cutoff = new Date(Date.now() - CUTOFF_DAYS * 24 * 60 * 60 * 1000)

  const { count: deleted } = await prisma.claudeJob.deleteMany({
    where: {
      status: { in: ['FAILED', 'CANCELLED', 'SKIPPED'] },
      finished_at: { lt: cutoff },
    },
  })

  return Response.json({ deleted, ran_at: new Date().toISOString() })
}
