File size: 1,300 Bytes
fbf3514
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { NextRequest, NextResponse } from "next/server";
import { getRazorpay } from "@/lib/razorpay";
import { createClient } from "@/lib/supabase/server";

export async function POST(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });

    const { data: profile } = await supabase
      .from("profiles")
      .select("razorpay_subscription_id")
      .eq("id", user.id)
      .single();

    if (!profile?.razorpay_subscription_id) {
      return NextResponse.json({ error: "No active subscription" }, { status: 400 });
    }

    const razorpay = getRazorpay();

    // Cancel at end of billing cycle (like Stripe's cancel_at_period_end)
    await razorpay.subscriptions.cancel(profile.razorpay_subscription_id, true);

    await supabase
      .from("profiles")
      .update({ updated_at: new Date().toISOString() })
      .eq("id", user.id);

    return NextResponse.json({ success: true, message: "Subscription will cancel at end of current period." });
  } catch (error: any) {
    console.error("Cancel error:", error);
    return NextResponse.json({ error: error.message || "Cancel failed" }, { status: 500 });
  }
}