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

export async function POST() {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
  const { userId, orgId } = ctx;

  const membership = await prisma.organizationMember.findFirst({
    where: { userId: userId, joinedAt: { not: null } },
    include: { organization: { include: { subscription: true } } },
  });

  const customerId = membership?.organization?.subscription?.stripeCustomerId;
  if (!customerId) return NextResponse.json({ success: false, error: "Aucun abonnement Stripe" }, { status: 404 });

  const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000";
  const portal = await createPortalSession(customerId, `${appUrl}/abonnement`);

  return NextResponse.json({ success: true, data: { url: portal.url } });
}
