import { getUserFromToken, readUsers, writeUsers, hasAnyRole } from '../../../utils/auth.js'
import { writeAuditLog } from '../../../utils/audit-log.js'

export default defineEventHandler(async (event) => {
  try {
    const token = getCookie(event, 'auth_token')
    const currentUser = await getUserFromToken(token)

    if (!currentUser || !hasAnyRole(currentUser, 'admin')) {
      throw createError({
        statusCode: 403,
        message: 'Zugriff verweigert'
      })
    }

    const body = await readBody(event)
    const { userId } = body

    const users = await readUsers()
    const updatedUsers = users.filter(u => u.id !== userId)
    
    await writeUsers(updatedUsers)

    await writeAuditLog('cms.user.rejected', {
      actorUserId: currentUser.id,
      targetUserId: userId
    })

    return {
      success: true,
      message: 'Registrierung wurde abgelehnt und gelöscht'
    }
  } catch (error) {
    console.error('Fehler beim Ablehnen:', error)
    throw error
  }
})

