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) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Not authenticated'
    })
  }

  let decoded
  try {
    decoded = jwt.verify(token, useRuntimeConfig().jwtSecret)
  } catch (err) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Invalid or expired token'
    })
  }

  const member = await Member.findById(decoded.memberId)

  if (!member) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Member not found'
    })
  }

  if (member.status === 'suspended' || member.status === 'cancelled') {
    throw createError({
      statusCode: 403,
      statusMessage: 'Account is ' + member.status
    })
  }

  if (decoded.tv !== member.tokenVersion) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Session has been revoked'
    })
  }

  // Issue a fresh token with current tokenVersion
  const newToken = jwt.sign(
    { memberId: member._id, email: member.email, tv: member.tokenVersion },
    useRuntimeConfig().jwtSecret,
    { expiresIn: '7d' }
  )

  setCookie(event, 'auth-token', newToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
    maxAge: 60 * 60 * 24 * 7, // 7 days
  })

  return { success: true }
})
