import mongoose from 'mongoose'
import Connection from '../../../models/connection.js'
import { requireAuth } from '../../../utils/auth.js'

export default defineEventHandler(async (event) => {
  const member = await requireAuth(event)
  const memberId = member._id
  const connectionId = getRouterParam(event, 'id')

  if (!mongoose.Types.ObjectId.isValid(connectionId)) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Invalid connection ID'
    })
  }

  const connection = await Connection.findById(connectionId)
  if (!connection) {
    throw createError({
      statusCode: 404,
      statusMessage: 'Connection not found'
    })
  }

  // Either party can hide
  const isParty =
    connection.initiator.toString() === memberId.toString() ||
    connection.recipient.toString() === memberId.toString()

  if (!isParty) {
    throw createError({
      statusCode: 403,
      statusMessage: 'Not authorized to hide this connection'
    })
  }

  // Add to hiddenBy if not already there
  const alreadyHidden = connection.hiddenBy.some(
    id => id.toString() === memberId.toString()
  )

  if (!alreadyHidden) {
    connection.hiddenBy.push(memberId)
    await connection.save()
  }

  return { success: true }
})
