All files / web/src/app/api/abacus/print/connections route.ts

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

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                                                                                                                                 
/**
 * Print-service connections (Abacus Studio Phase 2a, #8.2)
 *
 * GET  /api/abacus/print/connections - list the caller's connections (browser-safe views)
 * POST /api/abacus/print/connections - pair with a service via a CODE@host artifact
 */
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { getUserId } from '@/lib/viewer'
import { createConnectionFromPairing, listConnections } from '@/lib/abacus/print/connections'
import { PairingArtifactError } from '@/lib/abacus/print/pairing'
import { PrintServiceError } from '@/lib/abacus/print/print-service-fetch'

export const GET = withAuth(async () => {
  try {
    const userId = await getUserId()
    return NextResponse.json({ connections: await listConnections(userId) })
  } catch (error) {
    console.error('[print-connections] list failed:', error)
    return NextResponse.json({ error: 'Failed to list connections' }, { status: 500 })
  }
})

export const POST = withAuth(async (request, { userEmail }) => {
  try {
    const userId = await getUserId()
    const body = await request.json().catch(() => ({}))
    const artifact = typeof body.artifact === 'string' ? body.artifact : ''
    const name = typeof body.name === 'string' ? body.name : undefined
    if (!artifact.trim()) {
      return NextResponse.json({ error: 'Pairing code is required' }, { status: 400 })
    }

    const result = await createConnectionFromPairing({
      userId,
      artifact,
      name,
      userLabel: userEmail,
    })
    return NextResponse.json(result, { status: 201 })
  } catch (error) {
    if (error instanceof PrintServiceError) {
      // Codes are single-use with a short TTL — the actionable fix is always a fresh code.
      if (error.code === 'unreachable') {
        return NextResponse.json(
          { error: 'Could not reach the print service. Check the host and try again.' },
          { status: 502 }
        )
      }
      return NextResponse.json(
        {
          error:
            'Pairing failed — the code may be expired or already used. Get a fresh code from the print service and try again.',
        },
        { status: 400 }
      )
    }
    if (error instanceof PairingArtifactError) {
      return NextResponse.json({ error: error.message }, { status: 400 })
    }
    console.error('[print-connections] pairing failed:', error)
    return NextResponse.json({ error: 'Failed to create connection' }, { status: 500 })
  }
})