import { getDb } from '../../utils/db.js'
import { requireAuth } from '../../utils/authHelpers.js'

export default defineEventHandler(async (event) => {
  const currentUser = requireAuth(event, { role: 'admin' })
  const id = event.context.params?.id
  if (!id) throw createError({ statusCode: 400, message: 'id required' })

  if (id === currentUser.id) {
    throw createError({ statusCode: 400, message: 'Cannot delete your own account' })
  }

  const { run, get } = await getDb()
  const user = await get('SELECT id, auth_provider FROM users WHERE id = ?', [id])
  if (!user) throw createError({ statusCode: 404, message: 'User not found' })
  if (user.auth_provider !== 'local') {
    throw createError({ statusCode: 403, message: 'Only local users can be deleted' })
  }

  await run('DELETE FROM sessions WHERE user_id = ?', [id])
  await run('DELETE FROM users WHERE id = ?', [id])
  setResponseStatus(event, 204)
  return null
})
