import { NextRequest } from 'next/server'
import { eventEmitter } from '@/lib/event-emitter'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest) {
  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) {
      console.error('SSE send error', err)
    }
  }

  // Listener untuk event pembelian sukses
  const onPurchaseSuccess = (data: any) => {
    sendEvent('purchase_success', data)
  }

  eventEmitter.on('purchase_success', onPurchaseSuccess)

  req.signal.addEventListener('abort', () => {
    eventEmitter.off('purchase_success', onPurchaseSuccess)
    writer.close()
  })

  // Keep-alive ping every 15s to prevent timeout
  const keepAliveInterval = setInterval(() => {
    sendEvent('ping', { time: new Date().toISOString() })
  }, 15000)

  req.signal.addEventListener('abort', () => {
    clearInterval(keepAliveInterval)
  })

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