import { requireAuth } from '../../../utils/authHelpers.js'
import { getLiveSession } from '../../../utils/liveSessions.js'
import { getTransport } from '../../../utils/mediasoup.js'

export default defineEventHandler(async (event) => {
  const user = requireAuth(event) // Verify authentication
  const body = await readBody(event).catch(() => ({}))
  const { sessionId, transportId, dtlsParameters } = body

  if (!sessionId || !transportId || !dtlsParameters) {
    throw createError({ statusCode: 400, message: 'sessionId, transportId, and dtlsParameters required' })
  }

  const session = getLiveSession(sessionId)
  if (!session) {
    throw createError({ statusCode: 404, message: 'Session not found' })
  }

  // Verify user has permission to connect transport for this session
  // Only session owner or admin/leader can connect transports
  if (session.userId !== user.id && user.role !== 'admin' && user.role !== 'leader') {
    throw createError({ statusCode: 403, message: 'Forbidden' })
  }

  const transport = getTransport(transportId)
  if (!transport) {
    throw createError({ statusCode: 404, message: 'Transport not found' })
  }

  try {
    await transport.connect({ dtlsParameters })
    return { connected: true }
  }
  catch (err) {
    console.error('[connect-transport] Transport connect failed:', transportId, err.message || err)
    throw createError({ statusCode: 500, message: err.message || 'Transport connect failed' })
  }
})
