import jwt from 'jsonwebtoken'
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'

export default defineEventHandler(async (event) => {
  await connectDB()
  
  const token = getCookie(event, 'auth-token')
  if (!token) {
    return { authenticated: false, member: null }
  }
  
  try {
    const decoded = jwt.verify(token, useRuntimeConfig().jwtSecret)
    const member = await Member.findById(decoded.memberId).select('-__v')
    
    if (!member) {
      return { authenticated: false, member: null }
    }

    if (member.status === 'suspended' || member.status === 'cancelled') {
      return { authenticated: false, member: null }
    }

    return { 
      authenticated: true, 
      member: {
        id: member._id,
        email: member.email,
        name: member.name,
        circle: member.circle,
        status: member.status,
        contributionTier: member.contributionTier,
        membershipLevel: `${member.circle}-${member.contributionTier}`
      }
    }
  } catch (err) {
    return { authenticated: false, member: null }
  }
})