import { getUserFromToken } from '../../utils/auth.js'

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

    if (!token) {
      return {
        isLoggedIn: false,
        user: null,
        role: null
      }
    }

    const user = await getUserFromToken(token)

    if (!user) {
      deleteCookie(event, 'auth_token')
      return {
        isLoggedIn: false,
        user: null,
        role: null
      }
    }

    return {
      isLoggedIn: true,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role
      },
      role: user.role
    }
  } catch (error) {
    console.error('Auth-Status-Fehler:', error)
    return {
      isLoggedIn: false,
      user: null,
      role: null
    }
  }
})

