import { requireUserSession } from '../../utils/auth'
import { deleteUserById } from '../../database/queries/users'
import { handleApiError, createSuccessResponse } from '../../utils/errors'

export default defineEventHandler(async (event) => {
  try {
    // Get the authenticated user session
    const session = await requireUserSession(event)
    const userId = session.user.id

    // Better Auth's cascade delete should handle related records (accounts, sessions, verification tokens)
    await deleteUserById(userId)

    return createSuccessResponse({ userId }, 'Account deleted successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
