import { verifyToken, getUserById, hasAnyRole } from '../utils/auth.js'
import { promises as fs } from 'fs'
import path from 'path'

// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant ('config.json'), never user input
const getDataPath = (filename) => {
  const cwd = process.cwd()
  if (cwd.endsWith('.output')) {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    return path.join(cwd, '../server/data', filename)
  }
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  return path.join(cwd, 'server/data', filename)
}

export default defineEventHandler(async (event) => {
  try {
    const token = getCookie(event, 'auth_token')

    if (!token) {
      throw createError({
        statusCode: 401,
        message: 'Nicht authentifiziert.'
      })
    }

    const decoded = verifyToken(token)

    if (!decoded) {
      throw createError({
        statusCode: 401,
        message: 'Ungültiges Token.'
      })
    }

    const user = await getUserById(decoded.id)

    // Only admin and vorstand can edit config
    if (!user || !hasAnyRole(user, 'admin', 'vorstand')) {
      throw createError({
        statusCode: 403,
        message: 'Keine Berechtigung zum Bearbeiten der Konfiguration.'
      })
    }

    const body = await readBody(event)

    const configFile = getDataPath('config.json')
    await fs.writeFile(configFile, JSON.stringify(body, null, 2), 'utf-8')

    return {
      success: true,
      message: 'Konfiguration erfolgreich gespeichert.'
    }
  } catch (error) {
    console.error('Fehler beim Speichern der Config:', error)
    throw error
  }
})

