import Member from '../../../models/member.js'
import ActivityLog from '../../../models/activityLog.js'
import { connectDB } from '../../../utils/mongoose.js'

export default defineEventHandler(async (event) => {
  await connectDB()

  const id = getRouterParam(event, 'id')

  const member = await Member.findOne({
    _id: id,
    showInDirectory: true,
    status: 'active'
  }).lean()

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

  const query = getQuery(event)
  const limit = Math.min(parseInt(query.limit) || 5, 20)
  const before = query.before ? new Date(query.before) : null

  const filter = {
    member: member._id,
    visibility: 'public'
  }
  if (before) filter.timestamp = { $lt: before }

  const entries = await ActivityLog.find(filter)
    .sort({ timestamp: -1 })
    .limit(limit + 1)
    .lean()

  const hasMore = entries.length > limit
  if (hasMore) entries.pop()

  const nextCursor = hasMore && entries.length
    ? entries[entries.length - 1].timestamp.toISOString()
    : null

  return { entries, hasMore, nextCursor }
})
