import mongoose from 'mongoose'
import Connection from '../../../models/connection.js'
import Member from '../../../models/member.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 recipient can confirm
  if (connection.recipient.toString() !== memberId.toString()) {
    throw createError({
      statusCode: 403,
      statusMessage: 'Only the recipient can confirm a connection'
    })
  }

  if (connection.status !== 'pending') {
    throw createError({
      statusCode: 400,
      statusMessage: 'Connection is not pending'
    })
  }

  connection.status = 'confirmed'
  connection.confirmedAt = new Date()
  await connection.save()

  // Get initiator name for activity log
  const initiator = await Member.findById(connection.initiator)
    .select('name')
    .lean()

  logActivity(memberId, 'connection_confirmed', { memberName: initiator?.name || 'Unknown' })
  logActivity(connection.initiator, 'connection_confirmed', { memberName: member.name })

  return { connection }
})
