import type { WebNovel } from '~/types'

export default defineEventHandler(async (event): Promise<WebNovel[]> => {
  const query = getQuery(event)
  const search = (query.q as string || '').toLowerCase()
  const genre = query.genre as string
  const status = query.status as string

  let results = await queryCollection('content').all() as WebNovel[]

  // Filter to only index files
  results = results.filter(n => !n._path?.includes('/ch-')) as WebNovel[]

  if (search) {
    results = results.filter((novel) => {
      const title = (novel.title || '').toLowerCase()
      const description = (novel.description || '').toLowerCase()
      const authorName = (novel.author || '').toLowerCase()
      const tags = (novel.tags || []).map(t => (t || '').toLowerCase())

      return (
        title.includes(search)
        || description.includes(search)
        || authorName.includes(search)
        || tags.some(tag => tag.includes(search))
      )
    })
  }

  if (genre) {
    results = results.filter(novel =>
      (novel.genres || []).includes(genre)
    )
  }

  if (status) {
    results = results.filter(novel => novel.status === status)
  }

  return results.sort((a, b) =>
    new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime()
  ) as WebNovel[]
})
