/**
 * Real-time WebSocket connect route — real-time-infrastructure.
 *
 * GET /api/realtime/connect  → 101 Switching Protocols
 *
 * Same-origin handshake: the browser sends the HttpOnly session cookie
 * automatically, so the connection authenticates through the normal
 * authMiddleware — no token in the query string. After authentication the
 * upgrade is forwarded to the tenant's DO (TenantRealtimeDO) with a trusted
 * `X-User-Id` header so the DO can tag the socket for `targetUserId`-scoped
 * delivery. Non-WebSocket requests receive 426 Upgrade Required.
 */
import { Hono } from 'hono'
import type { AppEnv } from '../types'
import { authMiddleware } from '../middleware/auth'

export const realtimeRoutes = new Hono<AppEnv>()

realtimeRoutes.use('*', authMiddleware)

realtimeRoutes.get('/connect', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const upgrade = c.req.header('Upgrade')
  if (!upgrade || upgrade.toLowerCase() !== 'websocket') {
    return c.json({ error: 'Upgrade Required' }, 426)
  }

  // Forward the upgrade to the tenant DO, carrying the authenticated identity.
  const id = c.env.DO_REALTIME.idFromName(`tenant:${session.tid}`)
  const stub = c.env.DO_REALTIME.get(id)

  // Reconstruct the upgrade request with the trusted identity header. The
  // `Upgrade: websocket` header is copied from the original so the DO still
  // sees a handshake.
  const headers = new Headers(c.req.raw.headers)
  headers.set('X-User-Id', session.sub)
  return stub.fetch(new Request('https://do-internal/connect', {
    method: c.req.raw.method,
    headers,
  }))
})
