import type { APIRoute } from 'astro'

// Right to be Forgotten API - PDPA Article 17
// DELETE /api/consent?session_id=xxx - ลบข้อมูลของ session นี้

export const DELETE: APIRoute = async ({ request }) => {
  try {
    const url = new URL(request.url)
    const sessionId = url.searchParams.get('session_id')

    if (!sessionId) {
      return new Response(
        JSON.stringify({ error: 'session_id is required' }),
        { status: 400, headers: { 'Content-Type': 'application/json' } }
      )
    }

    // In Payload CMS, you would:
    // 1. Find all consent-logs with this sessionId
    // 2. Delete them
    // 3. Also delete any user data associated with this session

    // Example Payload query (for reference):
    // await payload.delete({
    //   collection: 'consent-logs',
    //   where: { sessionId: { equals: sessionId } },
    // })

    console.log(`[Right to be Forgotten] Deleting data for session: ${sessionId}`)

    return new Response(
      JSON.stringify({
        success: true,
        message: 'ข้อมูลของคุณถูกลบแล้ว',
        deletedAt: new Date().toISOString(),
      }),
      { status: 200, headers: { 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    console.error('[Right to be Forgotten] Error:', error)
    return new Response(
      JSON.stringify({ error: 'Internal server error' }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    )
  }
}

// GET /api/consent/export - ขอ export ข้อมูลของตัวเอง (PDPA Article 31)
export const GET: APIRoute = async ({ request }) => {
  try {
    const url = new URL(request.url)
    const sessionId = url.searchParams.get('session_id')

    if (!sessionId) {
      return new Response(
        JSON.stringify({ error: 'session_id is required' }),
        { status: 400, headers: { 'Content-Type': 'application/json' } }
      )
    }

    // In Payload CMS, query consent-logs for this session
    // Return the data as JSON for the user to review

    // Example Payload query (for reference):
    // const logs = await payload.find({
    //   collection: 'consent-logs',
    //   where: { sessionId: { equals: sessionId } },
    // })

    return new Response(
      JSON.stringify({
        success: true,
        message: 'ข้อมูลของคุณ',
        data: [], // Replace with actual Payload query result
        requestedAt: new Date().toISOString(),
      }),
      { status: 200, headers: { 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    console.error('[Consent Export] Error:', error)
    return new Response(
      JSON.stringify({ error: 'Internal server error' }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    )
  }
}
