import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@/payload.config'

/**
 * DELETE /api/consent - Right to be forgotten (GDPR/PDPA)
 *
 * Deletes all consent records for a given session or user
 */
export async function DELETE(request: NextRequest) {
  try {
    const payloadConfig = await config
    const payload = await getPayload({ config: payloadConfig })

    const { searchParams } = new URL(request.url)
    const sessionId = searchParams.get('sessionId')

    if (!sessionId) {
      return NextResponse.json({ error: 'sessionId is required' }, { status: 400 })
    }

    // Find and delete all consent logs for this session
    const result = await payload.delete({
      collection: 'consent-logs',
      where: {
        sessionId: { equals: sessionId },
      },
    })

    return NextResponse.json({
      success: true,
      deleted: result.deletedDocs?.length || 0,
      message: 'All consent records for this session have been deleted'
    })
  } catch (error) {
    console.error('Right to be forgotten error:', error)
    return NextResponse.json({ error: 'Failed to delete consent records' }, { status: 500 })
  }
}