import { writeFile, mkdir } from 'node:fs/promises'
import { join, dirname } from 'node:path'

export default defineEventHandler(async (event) => {
  const formData = await readMultipartFormData(event)

  if (!formData || formData.length === 0) {
    throw createError({ statusCode: 400, statusMessage: 'No files provided' })
  }

  const publicDir = join(process.cwd(), 'public')
  const uploaded: string[] = []

  for (const file of formData) {
    if (!file.filename || !file.data) continue

    // Sanitize filename
    const safeName = file.filename.replace(/[^a-zA-Z0-9._-]/g, '_')

    // Determine subdirectory from content type
    let subdir = 'uploads'
    const type = file.type ?? ''
    if (type.startsWith('image/')) subdir = 'images'
    else if (type.startsWith('audio/')) subdir = 'audio'
    else if (type === 'application/pdf') subdir = 'pdf'

    const targetDir = join(publicDir, subdir)
    await mkdir(targetDir, { recursive: true })

    const targetPath = join(targetDir, safeName)
    await writeFile(targetPath, file.data)

    uploaded.push(`/${subdir}/${safeName}`)
  }

  if (uploaded.length > 0) {
    gitSyncContent(`Upload média : ${uploaded.join(', ')}`, uploaded.map(f => `public${f}`))
  }

  return { ok: true, files: uploaded }
})
