import { requireAuth } from '../../utils/authHelpers.js'
import { getLiveSession, 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)
  const id = event.context.params?.id
  if (!id) throw createError({ statusCode: 400, message: 'id required' })

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

    // Clean up producer if it exists
    if (session.producerId) {
      const producer = getProducer(session.producerId)
      if (producer) {
        producer.close()
      }
    }

    // Clean up transport if it exists
    if (session.transportId) {
      const transport = getTransport(session.transportId)
      if (transport) {
        transport.close()
      }
    }

    // Clean up router
    await closeRouter(id)

    await deleteLiveSession(id)
    return { ok: true }
  })
})
