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

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

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                                                                                                                                   
import { eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { db, schema } from '@/db'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * POST /api/debug/billing-set-tier
 *
 * Sets the current user's tier for e2e testing.
 *
 * - { tier: 'free' }   → deletes subscription row (resolves to free)
 * - { tier: 'family' } → upserts subscription with plan: 'family', status: 'active'
 *
 * Admin-only (via route-policy.csv: /api/debug/* → admin).
 */
export const POST = withAuth(async (request, { userId }) => {
  const body = await request.json()
  const { tier } = body

  if (tier !== 'free' && tier !== 'family') {
    return NextResponse.json({ error: 'tier must be "free" or "family"' }, { status: 400 })
  }

  if (tier === 'free') {
    const deleted = await db
      .delete(schema.subscriptions)
      .where(eq(schema.subscriptions.userId, userId))
      .returning({ id: schema.subscriptions.id })

    return NextResponse.json({
      tier: 'free',
      action: deleted.length > 0 ? 'deleted' : 'already_free',
    })
  }

  // tier === 'family': upsert subscription row
  const now = new Date()
  await db
    .insert(schema.subscriptions)
    .values({
      userId,
      stripeCustomerId: `cus_test_${userId}`,
      stripeSubscriptionId: `sub_test_${userId}`,
      plan: 'family',
      status: 'active',
      currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
      cancelAtPeriodEnd: false,
      createdAt: now,
      updatedAt: now,
    })
    .onConflictDoUpdate({
      target: schema.subscriptions.userId,
      set: {
        plan: 'family',
        status: 'active',
        stripeCustomerId: `cus_test_${userId}`,
        stripeSubscriptionId: `sub_test_${userId}`,
        currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        cancelAtPeriodEnd: false,
        updatedAt: now,
      },
    })

  return NextResponse.json({ tier: 'family', action: 'upserted' })
})