/**
 * Pusher authentication endpoint
 *
 * This endpoint authenticates users for private Pusher channels.
 * Required for secure channel subscriptions.
 */

import { requireUserSession } from '../../../utils/auth'
import Pusher from 'pusher'

function getPusher(): Pusher | null {
  const appId = process.env.PUSHER_APP_ID
  const key = process.env.PUSHER_KEY
  const secret = process.env.PUSHER_SECRET
  const cluster = process.env.PUSHER_CLUSTER || 'eu'

  if (!appId || !key || !secret) {
    return null
  }

  return new Pusher({
    appId,
    key,
    secret,
    cluster,
    useTLS: true
  })
}

export default defineEventHandler(async (event) => {
  console.log('[Pusher Auth] Request received')

  try {
    const session = await requireUserSession(event)
    const body = await readBody(event) as { socket_id: string, channel_name: string }

    console.log('[Pusher Auth] Session user ID:', session.user.id)
    console.log('[Pusher Auth] Request body:', { socket_id: body.socket_id, channel_name: body.channel_name })
    console.log('[Pusher Auth] Expected channel:', `private-user-${session.user.id}`)

    const pusher = getPusher()
    if (!pusher) {
      console.error('[Pusher Auth] Pusher not configured - missing env vars')
      // Return error in format Pusher expects
      setResponseStatus(event, 500)
      return { error: 'Pusher not configured' }
    }

    // Only allow users to subscribe to their own private channel
    if (body.channel_name === `private-user-${session.user.id}`) {
      console.log('[Pusher Auth] ✅ Channel authorized, generating auth response')
      const auth = pusher.authorizeChannel(body.socket_id, body.channel_name)
      console.log('[Pusher Auth] Auth response generated:', { auth: !!auth.auth, hasChannelData: !!auth.channel_data })
      // Pusher expects the raw auth response: { auth: "...", channel_data?: "..." }
      return auth
    }

    console.warn('[Pusher Auth] ❌ Unauthorized channel:', body.channel_name, 'expected:', `private-user-${session.user.id}`)
    // Return error in format Pusher expects
    setResponseStatus(event, 403)
    return { error: 'Unauthorized channel' }
  } catch (error) {
    console.error('[Pusher Auth] ❌ Error:', error)
    // If it's an H3Error, return it directly (Pusher will handle it)
    if (error && typeof error === 'object' && 'statusCode' in error) {
      const h3Error = error as { statusCode: number, message?: string }
      const statusCode = h3Error.statusCode
      const message = h3Error.message || 'Authentication failed'
      console.error('[Pusher Auth] H3Error:', statusCode, message)
      setResponseStatus(event, statusCode)
      return { error: message }
    }
    // For other errors, return 500
    console.error('[Pusher Auth] Unknown error:', error)
    setResponseStatus(event, 500)
    return { error: 'Authentication failed' }
  }
})
