import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
import { prisma } from "@/lib/prisma";

export async function POST() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const userId = session.user.id;

  try {
    const subscription = await prisma.subscription.findUnique({
      where: { userId },
    });

    if (!subscription) {
      return NextResponse.json(
        { error: "No active subscription" },
        { status: 404 }
      );
    }

    if (!subscription.stripeId.startsWith("sub_test_")) {
      try {
        await stripe.subscriptions.update(subscription.stripeId, {
          cancel_at_period_end: true,
        });
      } catch (error) {
        console.warn("[cancel-subscription] Stripe cancellation failed, continuing with DB update", error);
      }
    }

    await prisma.subscription.update({
      where: { userId },
      data: {
        status: "canceled",
        canceledAt: new Date(),
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[cancel-subscription]", error);
    return NextResponse.json(
      { error: "Failed to cancel subscription" },
      { status: 500 }
    );
  }
}
