import { createReadStream } from 'node:fs'
import { stat } from 'node:fs/promises'
import { join, normalize } from 'node:path'

export default defineEventHandler(async (event) => {
  const file = decodeURIComponent(getRouterParam(event, 'file') ?? '')
  const exportsDir = join(useRuntimeConfig(event).dataDir, 'exports')
  const abs = normalize(join(exportsDir, file))
  if (!abs.startsWith(normalize(exportsDir) + '/') || !abs.endsWith('.pdf')) {
    throw createError({ statusCode: 400, statusMessage: 'Fichier invalide' })
  }
  let s
  try {
    s = await stat(abs)
  } catch {
    throw createError({ statusCode: 404, statusMessage: 'Export introuvable' })
  }
  setHeader(event, 'Content-Type', 'application/pdf')
  setHeader(event, 'Content-Length', s.size)
  setHeader(event, 'Content-Disposition', `attachment; filename="${file.replace(/"/g, '')}"`)
  return sendStream(event, createReadStream(abs))
})
