import { requireAuth } from '../../utils/authHelpers.js'
import {
  getOrCreateSession,
  getActiveSessionByUserId,
  deleteLiveSession,
} from '../../utils/liveSessions.js'
import { closeRouter, getProducer, getTransport } from '../../utils/mediasoup.js'
import { acquire } from '../../utils/asyncLock.js'

export default defineEventHandler(async (event) => {
  const user = requireAuth(event, { role: 'adminOrLeader' })
  const body = await readBody(event).catch(() => ({}))
  const label = typeof body?.label === 'string' ? body.label.trim().slice(0, 100) : ''

  // Atomically get or create session, replacing existing if needed
  return await acquire(`session-start-${user.id}`, async () => {
    const existing = await getActiveSessionByUserId(user.id)
    if (existing) {
      // Clean up existing session resources
      if (existing.producerId) {
        const producer = getProducer(existing.producerId)
        if (producer) producer.close()
      }
      if (existing.transportId) {
        const transport = getTransport(existing.transportId)
        if (transport) transport.close()
      }
      if (existing.routerId) {
        await closeRouter(existing.id).catch((err) => {
          console.error('[live.start] Error closing previous router:', err)
        })
      }
      await deleteLiveSession(existing.id)
      console.log('[live.start] Replaced previous session:', existing.id)
    }

    const session = await getOrCreateSession(user.id, label || `Live: ${user.identifier || 'User'}`)
    console.log('[live.start] Session ready:', { id: session.id, userId: user.id, label: session.label })
    return {
      id: session.id,
      label: session.label,
    }
  })
})
