import { getUserFromToken, readUsers, hasAnyRole, migrateUserRoles } from '../../../utils/auth.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 users = await readUsers()
    
    // Return users without passwords
    const safeUsers = users.map(u => {
      const migrated = migrateUserRoles({ ...u })
      const roles = Array.isArray(migrated.roles) ? migrated.roles : (migrated.role ? [migrated.role] : ['mitglied'])
      return {
        id: u.id,
        email: u.email,
        name: u.name,
        roles: roles,
        role: roles[0] || 'mitglied', // Rückwärtskompatibilität
        phone: u.phone || '',
        active: u.active,
        created: u.created,
        lastLogin: u.lastLogin
      }
    })

    return {
      users: safeUsers
    }
  } catch (error) {
    console.error('Fehler beim Laden der Benutzer:', error)
    throw error
  }
})

