import { getUserFromToken, readUsers, writeUsers, hasAnyRole, migrateUserRoles } from '../../../utils/auth.js'
import { writeAuditLog } from '../../../utils/audit-log.js'

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

    if (!currentUser || !hasAnyRole(currentUser, 'admin')) {
      throw createError({
        statusCode: 403,
        message: 'Zugriff verweigert'
      })
    }

    const body = await readBody(event)
    const { userId, roles } = body

    const validRoles = ['mitglied', 'vorstand', 'admin', 'newsletter', 'trainer']
    const rolesArray = Array.isArray(roles) ? roles : (roles ? [roles] : ['mitglied'])
    
    if (!rolesArray.every(r => validRoles.includes(r))) {
      throw createError({
        statusCode: 400,
        message: 'Ungültige Rolle(n)'
      })
    }

    const users = await readUsers()
    const user = users.find(u => u.id === userId)

    if (!user) {
      throw createError({
        statusCode: 404,
        message: 'Benutzer nicht gefunden'
      })
    }

    // Migriere Benutzer falls nötig
    migrateUserRoles(user)
    
    // Setze Rollen
    const oldRoles = Array.isArray(user.roles) ? [...user.roles] : []
    user.roles = rolesArray
    const updatedUsers = users.map(u => u.id === userId ? user : u)
    await writeUsers(updatedUsers)

    await writeAuditLog('cms.user.roles.updated', {
      actorUserId: currentUser.id,
      targetUserId: userId,
      oldRoles,
      newRoles: rolesArray
    })

    return {
      success: true,
      message: 'Rolle wurde aktualisiert'
    }
  } catch (error) {
    console.error('Fehler beim Aktualisieren der Rolle:', error)
    throw error
  }
})

