import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getInitialQuotaResetAt } from "@/lib/quota";
import { getSessionUser } from "@/lib/session";

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

  if (user.plan !== "PREMIUM") {
    return NextResponse.json({ error: "No active subscription to cancel" }, { status: 400 });
  }

  await prisma.user.update({
    where: { id: user.id },
    data: {
      plan: "FREE",
      cardLast4: null,
      subscribedAt: null,
      apiKeyHash: null,
      apiKeyPrefix: null,
      apiRateLimitBonus: 0,
      quotaResetAt: getInitialQuotaResetAt(),
    },
  });

  return NextResponse.json({ ok: true });
}
