import { NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { stripe, createStripeCustomer, createCheckoutSession } from "@/lib/stripe";
import { z } from "zod";

const schema = z.object({
  priceId: z.string().min(1),
});

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

  const body = await req.json();
  const parsed = schema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ success: false, error: "Données invalides" }, { status: 400 });

  const membership = await prisma.organizationMember.findFirst({
    where: { userId: userId, joinedAt: { not: null } },
    include: {
      organization: { include: { subscription: true } },
      user: { select: { email: true } },
    },
  });
  if (!membership) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { organization } = membership;
  let stripeCustomerId = organization.subscription?.stripeCustomerId;

  if (!stripeCustomerId) {
    const customer = await createStripeCustomer(
      membership.user?.email ?? "",
      organization.name,
      organization.id
    );
    stripeCustomerId = customer.id;

    await prisma.subscription.upsert({
      where: { organizationId: organization.id },
      update: { stripeCustomerId },
      create: { organizationId: organization.id, stripeCustomerId, plan: "FREE", status: "ACTIVE" },
    });
  }

  const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000";
  const checkoutSession = await createCheckoutSession({
    customerId: stripeCustomerId,
    priceId: parsed.data.priceId,
    organizationId: organization.id,
    successUrl: `${appUrl}/abonnement?success=true`,
    cancelUrl: `${appUrl}/abonnement`,
  });

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