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

// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant (e.g., 'newsletter.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)
}

const NEWSLETTERS_FILE = getDataPath('newsletters.json')

async function readNewsletters() {
  try {
    const data = await fs.readFile(NEWSLETTERS_FILE, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    if (error.code === 'ENOENT') {
      return []
    }
    throw error
  }
}

async function writeNewsletters(newsletters) {
  await fs.writeFile(NEWSLETTERS_FILE, JSON.stringify(newsletters, null, 2), 'utf-8')
}

export default defineEventHandler(async (event) => {
  try {
    // Authentifizierung prüfen
    const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace('Bearer ', '')
    
    if (!token) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Nicht authentifiziert'
      })
    }

    const user = await getUserFromToken(token)
    if (!user || !hasAnyRole(user, 'admin', 'vorstand', 'newsletter')) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Keine Berechtigung'
      })
    }

    const newsletterId = getRouterParam(event, 'id')
    const body = await readBody(event)

    const newsletters = await readNewsletters()
    const newsletterIndex = newsletters.findIndex(n => n.id === newsletterId)

    if (newsletterIndex === -1) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Newsletter nicht gefunden'
      })
    }

    // Nur Entwürfe können bearbeitet werden
    if (newsletters[newsletterIndex].status === 'sent') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Versendete Newsletter können nicht bearbeitet werden'
      })
    }

    // Update Newsletter
    newsletters[newsletterIndex] = {
      ...newsletters[newsletterIndex],
      ...body,
      updatedAt: new Date().toISOString(),
      updatedBy: user.id
    }

    await writeNewsletters(newsletters)

    return {
      success: true,
      message: 'Newsletter erfolgreich aktualisiert',
      newsletter: newsletters[newsletterIndex]
    }
  } catch (error) {
    console.error('Fehler beim Aktualisieren des Newsletters:', error)
    if (error.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Fehler beim Aktualisieren des Newsletters'
    })
  }
})

