import { requireAuth } from '../../../utils/authHelpers.js'
import { getLiveSession, updateLiveSession } from '../../../utils/liveSessions.js'
import { getTransport, producers } 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, transportId, kind, rtpParameters } = body

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

  return await acquire(`create-producer-${sessionId}`, async () => {
    const session = getLiveSession(sessionId)
    if (!session) {
      throw createError({ statusCode: 404, message: 'Session not found' })
    }
    if (session.userId !== user.id) {
      throw createError({ statusCode: 403, message: 'Forbidden' })
    }

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

    const producer = await transport.produce({ kind, rtpParameters })
    producers.set(producer.id, producer)
    producer.on('close', async () => {
      producers.delete(producer.id)
      const s = getLiveSession(sessionId)
      if (s && s.producerId === producer.id) {
        try {
          await updateLiveSession(sessionId, { producerId: null })
        }
        catch {
          // Ignore errors during cleanup
        }
      }
    })

    try {
      await updateLiveSession(sessionId, { producerId: producer.id })
    }
    catch (err) {
      if (err.message === 'Session not found') {
        throw createError({ statusCode: 404, message: 'Session not found' })
      }
      throw err
    }

    return {
      id: producer.id,
      kind: producer.kind,
    }
  })
})
