import { promises as fs } from 'fs'
import path from 'path'
import { getUserFromToken } from '../../utils/auth.js'

async function readPackageVersion() {
  const cwd = process.cwd()
  const candidatePaths = [
    path.join(cwd, 'package.json'),
    path.join(cwd, '../package.json')
  ]

  for (const packageJsonPath of candidatePaths) {
    try {
      const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'))
      if (packageJson?.version) {
        return String(packageJson.version)
      }
    } catch (_error) {
      // Try next candidate path (e.g. .output runtime)
    }
  }

  return ''
}

export default defineEventHandler(async (event) => {
  const token = getCookie(event, 'auth_token')
  const user = token ? await getUserFromToken(token) : null

  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Nicht authentifiziert'
    })
  }

  return {
    version: await readPackageVersion()
  }
})
