import WikiArticle from '../../models/wikiArticle.js'
import { connectDB } from '../../utils/mongoose.js'
import { requireAuth } from '../../utils/auth.js'

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

  // Combine craft tags and board topic tags
  const craftTags = member.craftTags || []
  const boardTags = (member.board?.topics || []).map(t => t.tagSlug)
  const memberTags = [...new Set([...craftTags, ...boardTags].filter(Boolean))]

  if (!memberTags.length) {
    return []
  }

  await connectDB()

  const query = getQuery(event)
  const limit = Math.min(Math.max(parseInt(query.limit) || 10, 1), 25)

  const articles = await WikiArticle.find({
    tags: { $in: memberTags },
    publishedAt: { $ne: null }
  })
    .sort({ publishedAt: -1 })
    .limit(limit)
    .select('title url summary tags collection publishedAt')
    .lean()

  return articles
})
