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

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

  const { collection, search } = getQuery(event)

  const filter = {}
  if (collection) {
    filter.collection = collection
  }
  if (search) {
    filter.title = { $regex: escapeRegex(search), $options: 'i' }
  }

  const articles = await WikiArticle.find(filter)
    .select('collection title tags hidden url outlineId publishedAt outlineUpdatedAt')
    .sort({ collection: 1, title: 1 })
    .lean()

  return articles
})
