import { unlink } from 'node:fs/promises'
import { join } from 'node:path'
import { getDb, getAvatarsDir } from '../../utils/db.js'
import { requireAuth } from '../../utils/authHelpers.js'

export default defineEventHandler(async (event) => {
  const user = requireAuth(event)
  if (!user.avatar_path) return { ok: true }

  // Validate avatar path to prevent path traversal attacks
  const filename = user.avatar_path
  if (!filename || !/^[a-f0-9-]+\.(?:jpg|jpeg|png)$/i.test(filename)) {
    throw createError({ statusCode: 400, message: 'Invalid avatar path' })
  }

  const path = join(getAvatarsDir(), filename)
  await unlink(path).catch(() => {})
  const { run } = await getDb()
  await run('UPDATE users SET avatar_path = NULL WHERE id = ?', [user.id])
  return { ok: true }
})
