import BoardChannel from '../../../models/boardChannel.js'
import { requireAdmin } from '../../../utils/auth.js'
import { validateBody } from '../../../utils/validateBody.js'
import { boardChannelUpdateSchema } from '../../../utils/schemas.js'

export default defineEventHandler(async (event) => {
  await requireAdmin(event)
  const id = getRouterParam(event, 'id')

  const body = await validateBody(event, boardChannelUpdateSchema)

  const updateData = {}
  if (body.name !== undefined) updateData.name = body.name
  if (body.slackChannelId !== undefined) updateData.slackChannelId = body.slackChannelId
  if (body.tagSlugs !== undefined) updateData.tagSlugs = body.tagSlugs

  if (body.tagSlugs && body.tagSlugs.length) {
    const conflict = await BoardChannel.findOne({
      _id: { $ne: id },
      tagSlugs: { $in: body.tagSlugs },
    }).lean()
    if (conflict) {
      const taken = (conflict.tagSlugs || []).filter((s) => body.tagSlugs.includes(s))
      throw createError({
        statusCode: 409,
        statusMessage: `Tag${taken.length > 1 ? 's' : ''} already mapped to "${conflict.name}": ${taken.join(', ')}`,
      })
    }
  }

  try {
    const channel = await BoardChannel.findByIdAndUpdate(
      id,
      { $set: updateData },
      { new: true, runValidators: true }
    )

    if (!channel) {
      throw createError({ statusCode: 404, statusMessage: 'Channel not found' })
    }

    return { channel: channel.toObject() }
  } catch (err) {
    if (err.statusCode) throw err
    if (err.code === 11000) {
      throw createError({
        statusCode: 409,
        statusMessage: 'A channel with that Slack channel ID already exists'
      })
    }
    throw err
  }
})
