import { verifyToken, getUserById } from '../utils/auth.js'

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

    if (!token) {
      throw createError({
        statusCode: 401,
        message: 'Nicht authentifiziert.'
      })
    }

    const decoded = verifyToken(token)

    if (!decoded) {
      throw createError({
        statusCode: 401,
        message: 'Ungültiges Token.'
      })
    }

    const user = await getUserById(decoded.id)

    if (!user || user.active === false) {
      throw createError({
        statusCode: 403,
        message: 'Benutzer nicht gefunden oder inaktiv.'
      })
    }

    // Return user data (without password)
    return {
      success: true,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        phone: user.phone || '',
        role: user.role
      }
    }
  } catch (error) {
    console.error('Profil-Abruf-Fehler:', error)
    throw error
  }
})

