import { NextResponse } from "next/server";
import { db, users, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getStripeClient } from "@/lib/stripe";

export async function POST() {
  const { session, response } = await requireSession();
  if (response) return response;

  const limited = await applyRateLimit(`rl:billing:portal:${session!.user.id}`, 10, 60);
  if (limited) return limited;

  const stripe = await getStripeClient();
  if (!stripe) {
    return NextResponse.json({ error: "Billing is not configured" }, { status: 400 });
  }

  const [dbUser] = await db.select({ stripeCustomerId: users.stripeCustomerId }).from(users).where(eq(users.id, session!.user.id)).limit(1);
  if (!dbUser?.stripeCustomerId) {
    return NextResponse.json({ error: "No billing account yet — subscribe first" }, { status: 400 });
  }

  const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
  const portalSession = await stripe.billingPortal.sessions.create({
    customer: dbUser.stripeCustomerId,
    return_url: `${baseUrl}/settings/billing`,
  });

  return NextResponse.json({ url: portalSession.url });
}
