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

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

  if (!currentUser) {
    throw createError({ statusCode: 401, statusMessage: 'Nicht authentifiziert' })
  }

  const body = await readBody(event)
  const credentialId = String(body?.credentialId || '')
  if (!credentialId) {
    throw createError({ statusCode: 400, statusMessage: 'credentialId fehlt' })
  }

  const users = await readUsers()
  const idx = users.findIndex(u => u.id === currentUser.id)
  if (idx === -1) {
    throw createError({ statusCode: 404, statusMessage: 'Benutzer nicht gefunden' })
  }

  const user = users[idx]
  const before = Array.isArray(user.passkeys) ? user.passkeys.length : 0
  user.passkeys = (Array.isArray(user.passkeys) ? user.passkeys : []).filter(pk => pk.credentialId !== credentialId)
  const after = user.passkeys.length
  users[idx] = user
  await writeUsers(users)

  await writeAuditLog('auth.passkey.removed', { userId: currentUser.id })

  return {
    success: true,
    removed: before !== after
  }
})


