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 {
    const now = new Date()

    // Delete projects where isDraft=true AND draftExpiresAt has passed
    const result = await prisma.project.deleteMany({
      where: {
        isDraft: true,
        draftExpiresAt: {
          lt: now,
        },
      },
    })

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