import ActivityLog from '../../../models/activityLog.js'

export default defineEventHandler(async (event) => {
  const member = await requireAuth(event)

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

  const filter = {
    member: member._id,
    visibility: { $in: ['member', '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 }
})
