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

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

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

    if (!hasAnyRole(currentUser, 'admin', 'vorstand')) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Keine Berechtigung'
      })
    }

    const { filename, content } = await readBody(event)
    
    if (!filename || !content) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Filename und Content sind erforderlich'
      })
    }
    
    // Sicherheitsprüfung: Nur bestimmte Dateien erlauben
    const allowedFiles = [
      'vereinsmeisterschaften.csv',
      'mannschaften.csv',
      'termine.csv',
      'spielplan.csv'
    ]
    
    if (!allowedFiles.includes(filename)) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Datei nicht erlaubt'
      })
    }
    
    // Handle both dev and production paths
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    // filename is validated against allowlist above, path traversal prevented
    const cwd = process.cwd()
    let filePath
    
    // In production (.output/server), working dir is .output
    if (cwd.endsWith('.output')) {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
      filePath = path.join(cwd, '../public/data', filename)
    } else {
      // In development, working dir is project root
      // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
      filePath = path.join(cwd, 'public/data', filename)
    }
    
    const dataDir = path.dirname(filePath)
    
    // Sicherstellen, dass das Verzeichnis existiert
    await fs.mkdir(dataDir, { recursive: true })
    
    // Datei schreiben
    await fs.writeFile(filePath, content, 'utf8')
    
    return {
      success: true,
      message: 'Datei erfolgreich gespeichert'
    }
    
  } catch (error) {
    console.error('Fehler beim Speichern der CSV-Datei:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Speichern der Datei'
    })
  }
})
