import { readCredentials, writeCredentials } from '../../../utils/adUserCredentials'

export default defineEventHandler(async (event) => {
  const userIdRaw = getCookie(event, 'logship_user_id')
  const token = getCookie(event, 'logship_it')
  const userId = Number(userIdRaw)
  if (!userId || !token) {
    throw createError({ statusCode: 401, statusMessage: 'Not authenticated' })
  }

  const body = await readBody(event).catch(() => ({} as any))
  const credentialId = String(body?.credentialId ?? '').trim()
  if (!credentialId) {
    throw createError({ statusCode: 400, statusMessage: 'Missing credentialId' })
  }

  const stored = await readCredentials(event, userId, token)
  const remaining = stored.keys.filter(k => k.credentialId !== credentialId)

  // If the user just deleted their last key, also drop the encrypted password —
  // there's no longer a way to use it.
  const payload = {
    keys: remaining,
    password: remaining.length === 0 ? null : stored.password,
  }
  await writeCredentials(event, userId, payload, token)

  return { status: 200, deleted: stored.keys.length - remaining.length }
})
