All files / app/api/subscription/downgrade route.ts

100% Statements 109/109
100% Branches 28/28
100% Functions 3/3
100% Lines 109/109

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 1521x           21x 21x 21x 20x     20x 20x 20x   21x 1x 1x   19x 19x         21x 1x 1x     18x 18x 18x 18x 18x   21x 1x 1x   17x     21x 6x 6x 6x 6x 6x   21x   2x 2x 2x 2x   2x 1x 1x 1x   1x 21x   9x 9x 9x 9x   9x 1x 1x 1x   8x 8x 21x 1x 1x 1x 21x   4x 4x 4x 3x   3x 3x 3x   4x 1x 1x     2x 2x 2x   4x 1x 1x 1x   1x 1x 1x 1x 1x 4x   5x 5x 5x 4x   4x 4x 4x   5x 1x 1x   3x 3x   5x 1x 1x     2x 2x 2x 2x   5x 1x 1x 1x   1x 1x 1x 1x 1x 5x  
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getAdminClient } from '@/lib/supabase/admin';
import { canDowngradeTo } from '@/lib/subscription/downgrade';
import type { SubscriptionTier } from '@/types/database';
 
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const adminClient = getAdminClient();
 
    // Get authenticated user
    const {
      data: { user },
    } = await supabase.auth.getUser();
 
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    const body = await request.json();
    const { target_tier, immediate } = body as {
      target_tier: SubscriptionTier;
      immediate?: boolean;
    };
 
    if (!target_tier) {
      return NextResponse.json({ error: 'target_tier is required' }, { status: 400 });
    }
 
    // Get current profile and subscription
    const { data: profile } = await supabase
      .from('profiles')
      .select('subscription_tier')
      .eq('user_id', user.id)
      .single();
 
    if (!profile) {
      return NextResponse.json({ error: 'Profile not found' }, { status: 404 });
    }
 
    const currentTier = profile.subscription_tier as SubscriptionTier;
 
    // Validate downgrade
    if (!canDowngradeTo(currentTier, target_tier)) {
      return NextResponse.json(
        { error: 'Invalid downgrade: target tier must be lower than current tier' },
        { status: 400 }
      );
    }
 
    if (immediate) {
      // Process immediate downgrade
      const { data, error } = await adminClient.rpc('process_immediate_downgrade', {
        p_user_id: user.id,
        p_target_tier: target_tier,
      });
 
      if (error) {
        console.error('Immediate downgrade error:', error);
        return NextResponse.json({ error: 'Failed to process downgrade' }, { status: 500 });
      }
 
      return NextResponse.json(data);
    } else {
      // Schedule downgrade for end of period
      const { data, error } = await adminClient.rpc('schedule_downgrade', {
        p_user_id: user.id,
        p_target_tier: target_tier,
      });
 
      if (error) {
        console.error('Schedule downgrade error:', error);
        return NextResponse.json({ error: 'Failed to schedule downgrade' }, { status: 500 });
      }
 
      return NextResponse.json(data);
    }
  } catch (error) {
    console.error('Downgrade API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
 
export async function DELETE(_request: NextRequest) {
  try {
    const supabase = await createClient();
    const adminClient = getAdminClient();
 
    const {
      data: { user },
    } = await supabase.auth.getUser();
 
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    // Cancel scheduled downgrade
    const { data, error } = await adminClient.rpc('cancel_scheduled_downgrade', {
      p_user_id: user.id,
    });
 
    if (error) {
      console.error('Cancel downgrade error:', error);
      return NextResponse.json({ error: 'Failed to cancel downgrade' }, { status: 500 });
    }
 
    return NextResponse.json(data);
  } catch (error) {
    console.error('Cancel downgrade API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
 
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const adminClient = getAdminClient();
 
    const {
      data: { user },
    } = await supabase.auth.getUser();
 
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
 
    const url = new URL(request.url);
    const targetTier = url.searchParams.get('target_tier') as SubscriptionTier;
 
    if (!targetTier) {
      return NextResponse.json({ error: 'target_tier query param is required' }, { status: 400 });
    }
 
    // Get downgrade impact
    const { data, error } = await adminClient.rpc('get_downgrade_impact', {
      p_user_id: user.id,
      p_target_tier: targetTier,
    });
 
    if (error) {
      console.error('Get impact error:', error);
      return NextResponse.json({ error: 'Failed to calculate impact' }, { status: 500 });
    }
 
    return NextResponse.json(data);
  } catch (error) {
    console.error('Get impact API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}