import { requireAuth } from '../../../utils/authHelpers.js'
import { getLiveSession } from '../../../utils/liveSessions.js'
import { getRouter, getTransport, getProducer, createConsumer } from '../../../utils/mediasoup.js'

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

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

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

  // Authorization check: only session owner or admin/leader can consume
  if (session.userId !== user.id && user.role !== 'admin' && user.role !== 'leader') {
    throw createError({ statusCode: 403, message: 'Forbidden' })
  }

  if (!session.producerId) {
    throw createError({ statusCode: 404, message: 'No producer available for this session' })
  }

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

  const producer = getProducer(session.producerId)
  if (!producer) {
    console.error('[create-consumer] Producer not found:', session.producerId)
    throw createError({ statusCode: 404, message: `Producer not found: ${session.producerId}` })
  }

  if (producer.paused) {
    await producer.resume()
  }

  if (producer.closed) {
    throw createError({ statusCode: 404, message: 'Producer is closed' })
  }

  const router = await getRouter(sessionId)
  const canConsume = router.canConsume({ producerId: producer.id, rtpCapabilities })
  if (!canConsume) {
    throw createError({ statusCode: 400, message: 'Cannot consume this producer' })
  }

  try {
    const { params } = await createConsumer(transport, producer, rtpCapabilities)
    return params
  }
  catch (err) {
    console.error('[create-consumer] Error creating consumer:', err)
    throw createError({ statusCode: 500, message: `Failed to create consumer: ${err.message || String(err)}` })
  }
})
