import * as z from 'zod'
import WikiArticle from '../../../models/wikiArticle.js'
import { connectDB } from '../../../utils/mongoose.js'

const batchTagSchema = z.object({
  articleIds: z.array(z.string()).optional(),
  collection: z.string().optional(),
  addTags: z.array(z.string()).optional(),
  removeTags: z.array(z.string()).optional()
})

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

  const body = await validateBody(event, batchTagSchema)

  if (!body.articleIds && !body.collection) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Must provide either articleIds or collection'
    })
  }

  if (!body.addTags?.length && !body.removeTags?.length) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Must provide at least one of addTags or removeTags'
    })
  }

  await connectDB()

  await validateTagSlugs([...(body.addTags || []), ...(body.removeTags || [])])

  const filter = body.articleIds
    ? { _id: { $in: body.articleIds } }
    : { collection: body.collection }

  let modified = 0

  if (body.addTags?.length) {
    const result = await WikiArticle.updateMany(filter, {
      $addToSet: { tags: { $each: body.addTags } }
    })
    modified = result.modifiedCount || 0
  }

  if (body.removeTags?.length) {
    const result = await WikiArticle.updateMany(filter, {
      $pull: { tags: { $in: body.removeTags } }
    })
    // Use the higher count if both operations ran
    modified = Math.max(modified, result.modifiedCount || 0)
  }

  return { modified }
})
