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 configFile = getDataPath('config.json')
    const data = await fs.readFile(configFile, 'utf-8')
    const config = JSON.parse(data)

    return config
  } catch (error) {
    console.error('Fehler beim Laden der Config:', error)
    throw createError({
      statusCode: 500,
      message: 'Fehler beim Laden der Konfiguration.'
    })
  }
})

