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 [confirmed, pendingOutgoing, pendingIncoming] = await Promise.all([
    Connection.find({
      status: 'confirmed',
      hiddenBy: { $ne: memberId },
      $or: [
        { initiator: memberId },
        { recipient: memberId }
      ]
    })
      .populate('initiator recipient', 'name avatar craftTags circle')
      .sort({ confirmedAt: -1 })
      .lean(),

    Connection.find({
      initiator: memberId,
      status: 'pending',
      hiddenBy: { $ne: memberId }
    })
      .populate('recipient', 'name avatar craftTags circle')
      .sort({ createdAt: -1 })
      .lean(),

    Connection.find({
      recipient: memberId,
      status: 'pending',
      hiddenBy: { $ne: memberId }
    })
      .populate('initiator', 'name avatar craftTags circle')
      .sort({ createdAt: -1 })
      .lean()
  ])

  return {
    confirmed,
    pendingOutgoing,
    pendingIncoming
  }
})
