import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { eventEmitter } from '@/lib/event-emitter'

export const dynamic = 'force-dynamic'

export async function GET(
  req: NextRequest,
  { params }: { params: { roomId: string } }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return new Response('Unauthorized', { status: 401 })
  }

  const { roomId } = params
  const isAdmin = session.user.role === 'ADMIN'

  // Verifikasi akses ke room
  const room = await prisma.chatRoom.findUnique({ where: { id: roomId } })
  if (!room) return new Response('Room not found', { status: 404 })
  if (!isAdmin && room.userId !== session.user.id) return new Response('Forbidden', { status: 403 })

  let responseStream = new TransformStream()
  const writer = responseStream.writable.getWriter()
  const encoder = new TextEncoder()

  const sendEvent = async (eventName: string, data: any) => {
    try {
      await writer.write(encoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`))
    } catch (err) {
      // Client sudah disconnect
    }
  }

  const onMessage = (data: any) => {
    sendEvent('new_message', data)
  }

  eventEmitter.on(`chat_message_${roomId}`, onMessage)

  // Keep-alive
  const keepAlive = setInterval(() => {
    sendEvent('ping', { time: new Date().toISOString() })
  }, 15000)

  req.signal.addEventListener('abort', () => {
    eventEmitter.off(`chat_message_${roomId}`, onMessage)
    clearInterval(keepAlive)
    writer.close().catch(() => {})
  })

  return new Response(responseStream.readable, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache, no-transform',
      'Connection': 'keep-alive',
    },
  })
}
