import { getLiveSession, updateLiveSession } from './liveSessions.js'
import { getRouter, createTransport, getTransport } from './mediasoup.js'

export async function handleWebSocketMessage(userId, sessionId, type, data) {
  const session = getLiveSession(sessionId)
  if (!session) {
    return { error: 'Session not found' }
  }

  if (['create-transport', 'connect-transport'].includes(type) && session.userId !== userId) {
    return { error: 'Forbidden' }
  }

  try {
    switch (type) {
      case 'get-router-rtp-capabilities': {
        const router = await getRouter(sessionId)
        return { type: 'router-rtp-capabilities', data: router.rtpCapabilities }
      }
      case 'create-transport': {
        const router = await getRouter(sessionId)
        const { transport, params } = await createTransport(router)
        try {
          await updateLiveSession(sessionId, { transportId: transport.id, routerId: router.id })
        }
        catch (err) {
          if (err.message === 'Session not found') {
            return { error: 'Session not found' }
          }
          throw err
        }
        return { type: 'transport-created', data: params }
      }
      case 'connect-transport': {
        const { transportId, dtlsParameters } = data
        if (!transportId || !dtlsParameters) {
          return { error: 'transportId and dtlsParameters required' }
        }
        const transport = getTransport(transportId)
        if (!transport) {
          return { error: 'Transport not found' }
        }
        await transport.connect({ dtlsParameters })
        return { type: 'transport-connected', data: { connected: true } }
      }
      default:
        return { error: `Unknown message type: ${type}` }
    }
  }
  catch (err) {
    console.error('[webrtc-signaling] Error:', err)
    return { error: err.message || 'Internal error' }
  }
}
