import { NextResponse } from "next/server";
import Stripe from "stripe";
import { createClient } from "@supabase/supabase-js";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
// const supabase = createClient(process.env.SUPABASE_SERVICE_ROLE_KEY);

export async function POST(request) {
  try {
    const { subscriptionId } = await request.json();

    // Cancel the subscription in Stripe
    const cancelledSubscription = await stripe.subscriptions.cancel(
      subscriptionId
    );
    console.log(cancelledSubscription);

    // Update the subscription status in Supabase
    // const { error } = await supabase
    //   .from("subscription_data")
    //   .update({
    //     status: cancelledSubscription.status,
    //     active_subscription: false,
    //     current_period_end: new Date(
    //       cancelledSubscription.current_period_end * 1000
    //     ).toISOString(),
    //     current_period_start: new Date(
    //       cancelledSubscription.current_period_start * 1000
    //     ).toISOString(),
    //   })
    //   .eq("subscription_id", subscriptionId);

    // if (error) {
    //   console.error("Error updating subscription data in Supabase:", error);
    //   return NextResponse.json(
    //     {
    //       success: false,
    //       error: "Failed to update subscription data when cancelling",
    //     },
    //     { status: 500 }
    //   );
    // }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error cancelling subscription:", error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}
