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'
    })
  }

  // Only the initiator can withdraw
  if (connection.initiator.toString() !== memberId.toString()) {
    throw createError({
      statusCode: 403,
      statusMessage: 'Only the initiator can withdraw a connection request'
    })
  }

  if (connection.status !== 'pending') {
    throw createError({
      statusCode: 400,
      statusMessage: 'Can only withdraw pending connections'
    })
  }

  await Connection.findByIdAndDelete(connectionId)

  return { success: true }
})
