All files / web/src/app/api/notifications/subscriptions route.ts

0% Statements 0/205
0% Branches 0/1
0% Functions 0/1
0% Lines 0/205

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                                                                                                                                                                                                                                                                                                                                                                                                                           
import { NextResponse, type NextRequest } from 'next/server'
import { and, eq } from 'drizzle-orm'
import { withAuth } from '@/lib/auth/withAuth'
import { db } from '@/db'
import { practiceNotificationSubscriptions, users } from '@/db/schema'
import { canPerformAction } from '@/lib/classroom/access-control'
import { validateSessionShare } from '@/lib/session-share'
import {
  createSubscription,
  getActiveSubscriptionsForPlayer,
  getActiveSubscriptionsForUser,
} from '@/lib/notifications/subscription-manager'
import type { SubscriptionChannels, WebPushSubscriptionJson } from '@/db/schema'

const MAX_ANONYMOUS_SUBS_PER_PLAYER = 10
const ANONYMOUS_EXPIRY_DAYS = 30

/**
 * POST /api/notifications/subscriptions
 *
 * Create a new notification subscription.
 * - Authenticated users: verify canPerformAction(userId, playerId, 'view')
 * - Anonymous users: require valid shareToken, at least one delivery mechanism,
 *   30-day auto-expiry, max 10 anonymous subs per player
 */
export const POST = withAuth(async (request: NextRequest, { userId, userRole }) => {
  try {
    const body = await request.json()
    const { playerId, pushSubscription, shareToken, email, label, channels } = body as {
      playerId: string
      pushSubscription?: WebPushSubscriptionJson
      shareToken?: string
      email?: string
      label?: string
      channels?: SubscriptionChannels
    }

    if (!playerId) {
      return NextResponse.json({ error: 'playerId is required' }, { status: 400 })
    }

    const resolvedChannels: SubscriptionChannels = channels ?? {
      webPush: !!pushSubscription,
      email: !!email,
      inApp: false,
    }

    const isAuthenticated = userRole !== 'guest' && !!userId

    // Check if user has direct access to this player
    let hasDirectAccess = false
    if (isAuthenticated) {
      hasDirectAccess = await canPerformAction(userId!, playerId, 'view')
    }

    // Fall back to share token validation if no direct access
    if (!hasDirectAccess && shareToken) {
      const validation = await validateSessionShare(shareToken)
      if (validation.valid && validation.share?.playerId === playerId) {
        hasDirectAccess = true
      }
    }

    if (!hasDirectAccess) {
      if (!shareToken) {
        return NextResponse.json(
          { error: 'shareToken is required when you do not have direct access to this player' },
          { status: 400 }
        )
      }
      return NextResponse.json({ error: 'Not authorized for this player' }, { status: 403 })
    }

    if (isAuthenticated) {
      const result = await createSubscription({
        userId,
        playerId,
        email,
        pushSubscription,
        channels: resolvedChannels,
        label,
      })

      if (!result.success) {
        return NextResponse.json({ error: result.error }, { status: 400 })
      }

      return NextResponse.json({ subscription: result.subscription }, { status: 201 })
    } else {
      // Anonymous flow: require at least one delivery mechanism
      if (!pushSubscription && !email) {
        return NextResponse.json(
          { error: 'Anonymous subscriptions require a push subscription or email' },
          { status: 400 }
        )
      }

      // If the email belongs to an existing user, associate the subscription
      // with their account (no expiry, in-app enabled)
      if (email) {
        const [existingUser] = await db
          .select({ id: users.id })
          .from(users)
          .where(eq(users.email, email))
          .limit(1)

        if (existingUser) {
          resolvedChannels.inApp = true

          const result = await createSubscription({
            userId: existingUser.id,
            playerId,
            email,
            pushSubscription,
            channels: resolvedChannels,
            label,
          })

          if (!result.success) {
            return NextResponse.json({ error: result.error }, { status: 400 })
          }

          return NextResponse.json({ subscription: result.subscription }, { status: 201 })
        }
      }

      // Truly anonymous: rate limit and auto-expire
      const existingAnonymous = await db
        .select({ id: practiceNotificationSubscriptions.id })
        .from(practiceNotificationSubscriptions)
        .where(
          and(
            eq(practiceNotificationSubscriptions.playerId, playerId),
            eq(practiceNotificationSubscriptions.status, 'active')
          )
        )

      const anonymousCount = existingAnonymous.length
      if (anonymousCount >= MAX_ANONYMOUS_SUBS_PER_PLAYER) {
        return NextResponse.json(
          { error: `Maximum of ${MAX_ANONYMOUS_SUBS_PER_PLAYER} subscriptions per player reached` },
          { status: 429 }
        )
      }

      const expiresAt = new Date()
      expiresAt.setDate(expiresAt.getDate() + ANONYMOUS_EXPIRY_DAYS)

      const result = await createSubscription({
        playerId,
        email,
        pushSubscription,
        channels: resolvedChannels,
        label,
        expiresAt,
      })

      if (!result.success) {
        return NextResponse.json({ error: result.error }, { status: 400 })
      }

      return NextResponse.json({ subscription: result.subscription }, { status: 201 })
    }
  } catch (error) {
    console.error('[notifications] Failed to create subscription:', error)
    return NextResponse.json({ error: 'Failed to create subscription' }, { status: 500 })
  }
})

/**
 * GET /api/notifications/subscriptions?playerId=X
 *
 * List subscriptions for the authenticated user + specified player.
 */
export const GET = withAuth(async (request: NextRequest, { userId, userRole }) => {
  try {
    if (userRole === 'guest' || !userId) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
    }

    const { searchParams } = new URL(request.url)
    const playerId = searchParams.get('playerId')

    // When playerId is omitted, return all active subscriptions for the user
    if (!playerId) {
      const subscriptions = await getActiveSubscriptionsForUser(userId)
      return NextResponse.json({ subscriptions })
    }

    const canView = await canPerformAction(userId, playerId, 'view')
    if (!canView) {
      return NextResponse.json({ error: 'Not authorized for this player' }, { status: 403 })
    }

    const subscriptions = await getActiveSubscriptionsForPlayer(playerId)

    // Filter to only the current user's subscriptions
    const userSubs = subscriptions.filter((s) => s.userId === userId)

    return NextResponse.json({ subscriptions: userSubs })
  } catch (error) {
    console.error('[notifications] Failed to list subscriptions:', error)
    return NextResponse.json({ error: 'Failed to list subscriptions' }, { status: 500 })
  }
})