import Member from '../../models/member.js'

export default defineEventHandler(async (event) => {
  // Increment tokenVersion to invalidate all outstanding session tokens
  try {
    const member = await requireAuth(event)
    await Member.findByIdAndUpdate(member._id, { $inc: { tokenVersion: 1 } }, { runValidators: false })
  } catch {
    // Already unauthenticated — still clear the cookie
  }

  setCookie(event, 'auth-token', '', {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
    maxAge: 0,
  })

  return { message: 'Logged out successfully' }
})
