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

const MIME = Object.freeze({ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png' })

export default defineEventHandler(async (event) => {
  const user = requireAuth(event)
  if (!user.avatar_path) throw createError({ statusCode: 404, message: 'No avatar' })

  // 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)
  const ext = filename.split('.').pop()?.toLowerCase()
  const mime = MIME[ext] ?? 'application/octet-stream'
  try {
    const buf = await readFile(path)
    setResponseHeader(event, 'Content-Type', mime)
    setResponseHeader(event, 'Cache-Control', 'private, max-age=3600')
    return buf
  }
  catch {
    throw createError({ statusCode: 404, message: 'Avatar not found' })
  }
})
