All files / web/src/app/api/debug/billing-sync route.ts

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

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                                                                                     
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { syncCheckoutSession } from '@/lib/billing-sync'
import { getStripe } from '@/lib/stripe'

/**
 * POST /api/debug/billing-sync
 *
 * Finds the most recent completed Stripe checkout session for the current
 * user and syncs it to the local database. Useful when the verify-on-redirect
 * flow fails (e.g., wrong redirect URL, network issue).
 *
 * Admin-only (via route-policy.csv: /api/debug/* → admin).
 */
export const POST = withAuth(async (_request, { userId }) => {
  const stripe = getStripe()

  // List recent completed checkout sessions and find one for this user
  const sessions = await stripe.checkout.sessions.list({
    limit: 20,
    status: 'complete',
  })

  const match = sessions.data.find(
    (s) => s.client_reference_id === userId || s.metadata?.userId === userId
  )

  if (!match) {
    return NextResponse.json(
      { error: 'No completed checkout session found for your user' },
      { status: 404 }
    )
  }

  await syncCheckoutSession(match.id)

  return NextResponse.json({
    synced: true,
    sessionId: match.id,
    subscriptionId: match.subscription,
  })
})