import { auth } from '@/auth'
import { NextRequest, NextResponse } from 'next/server'

// In-memory signaling store (use Redis for multi-instance deployments)
const signalingStore = new Map<string, {
  offer?: RTCSessionDescriptionInit
  answer?: RTCSessionDescriptionInit
  viewerCandidates: RTCIceCandidateInit[]
  hostCandidates: RTCIceCandidateInit[]
  createdAt: number
}>()

function cleanupOldSessions() {
  const now = Date.now()
  for (const [key, value] of signalingStore.entries()) {
    if (now - value.createdAt > 5 * 60 * 1000) signalingStore.delete(key)
  }
}

export async function POST(request: NextRequest) {
  try {
    const session = await auth()
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { action, sessionId, data } = await request.json()
    cleanupOldSessions()

    switch (action) {
      case 'create-session':
        signalingStore.set(sessionId, { viewerCandidates: [], hostCandidates: [], createdAt: Date.now() })
        return NextResponse.json({ success: true })

      case 'send-offer': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        s.offer = data.offer
        return NextResponse.json({ success: true })
      }

      case 'get-offer': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        return NextResponse.json({ offer: s.offer ?? null })
      }

      case 'send-answer': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        s.answer = data.answer
        return NextResponse.json({ success: true })
      }

      case 'get-answer': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        return NextResponse.json({ answer: s.answer ?? null })
      }

      case 'send-ice-candidate': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        if (data.role === 'viewer') s.viewerCandidates.push(data.candidate)
        else s.hostCandidates.push(data.candidate)
        return NextResponse.json({ success: true })
      }

      case 'get-ice-candidates': {
        const s = signalingStore.get(sessionId)
        if (!s) return NextResponse.json({ error: 'Session not found' }, { status: 404 })
        const candidates = data.role === 'viewer' ? s.hostCandidates : s.viewerCandidates
        if (data.role === 'viewer') s.hostCandidates = []
        else s.viewerCandidates = []
        return NextResponse.json({ candidates })
      }

      case 'close-session':
        signalingStore.delete(sessionId)
        return NextResponse.json({ success: true })

      default:
        return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
    }
  } catch (error) {
    console.error('[Signal] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
