import { getRequestURL } from 'h3'
import { requireAuth } from '../../../utils/authHelpers.js'
import { getLiveSession, updateLiveSession } from '../../../utils/liveSessions.js'
import { getRouter, createTransport } from '../../../utils/mediasoup.js'
import { acquire } from '../../../utils/asyncLock.js'

export default defineEventHandler(async (event) => {
  const user = requireAuth(event)
  const body = await readBody(event).catch(() => ({}))
  const { sessionId, isProducer } = body

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

  return await acquire(`create-transport-${sessionId}`, async () => {
    const session = getLiveSession(sessionId)
    if (!session) {
      throw createError({ statusCode: 404, message: 'Session not found' })
    }

    // Only publisher (session owner) can create producer transport
    // Viewers can create consumer transports
    if (isProducer && session.userId !== user.id) {
      throw createError({ statusCode: 403, message: 'Forbidden' })
    }

    const url = getRequestURL(event)
    const requestHost = url.hostname
    const router = await getRouter(sessionId)
    const { transport, params } = await createTransport(router, requestHost)

    if (isProducer) {
      try {
        await updateLiveSession(sessionId, {
          transportId: transport.id,
          routerId: router.id,
        })
      }
      catch (err) {
        if (err.message === 'Session not found') {
          throw createError({ statusCode: 404, message: 'Session not found' })
        }
        throw err
      }
    }

    return params
  })
})
