All files / web/src/app/api/entry-prompts route.ts

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

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                                                                                                                                                         
import { and, eq, gt, inArray } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { db, schema } from '@/db'
import { getLinkedChildren } from '@/lib/classroom'
import { getUserId } from '@/lib/viewer'

/**
 * GET /api/entry-prompts
 * Get pending entry prompts for the current user's children (parent view)
 *
 * Returns active (pending + not expired) prompts for all children linked to the viewer
 */
export const GET = withAuth(async () => {
  try {
    const userId = await getUserId()

    // Get children linked to this user (parent)
    const children = await getLinkedChildren(userId)
    if (children.length === 0) {
      return NextResponse.json({ prompts: [] })
    }

    const childIds = children.map((c) => c.id)

    // Get pending prompts for these children
    const now = new Date()
    const prompts = await db.query.entryPrompts.findMany({
      where: and(
        inArray(schema.entryPrompts.playerId, childIds),
        eq(schema.entryPrompts.status, 'pending'),
        gt(schema.entryPrompts.expiresAt, now)
      ),
    })

    // Get additional info for display (classroom names, player info)
    const enrichedPrompts = await Promise.all(
      prompts.map(async (prompt) => {
        const [classroom, player, teacher] = await Promise.all([
          db.query.classrooms.findFirst({
            where: eq(schema.classrooms.id, prompt.classroomId),
          }),
          db.query.players.findFirst({
            where: eq(schema.players.id, prompt.playerId),
          }),
          db.query.users.findFirst({
            where: eq(schema.users.id, prompt.teacherId),
          }),
        ])

        return {
          ...prompt,
          expiresAt: prompt.expiresAt.toISOString(),
          createdAt: prompt.createdAt.toISOString(),
          player: {
            id: player?.id ?? prompt.playerId,
            name: player?.name ?? 'Unknown student',
            emoji: player?.emoji ?? '👤',
          },
          classroom: {
            id: classroom?.id ?? prompt.classroomId,
            name: classroom?.name ?? 'Unknown classroom',
          },
          teacher: {
            displayName: teacher?.name ?? 'Your teacher',
          },
        }
      })
    )

    return NextResponse.json({ prompts: enrichedPrompts })
  } catch (error) {
    console.error('Failed to fetch entry prompts:', error)
    return NextResponse.json({ error: 'Failed to fetch entry prompts' }, { status: 500 })
  }
})