import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getReferralDiscountPct } from "@/lib/referral";

/** Public endpoint for the landing page pricing section:
 *  - without a code: the program's configured discount percentage, so the
 *    cards can advertise the referral offer to every visitor;
 *  - with ?code=: is this subscriber code valid, and what does it grant?
 *    Only active subscribers' codes count. */
export async function GET(req: Request) {
  try {
    const code = (new URL(req.url).searchParams.get("code") ?? "").trim().toUpperCase();
    const discountPct = await getReferralDiscountPct();
    if (!code || discountPct <= 0) {
      return NextResponse.json({ valid: false, discountPct });
    }
    const referrer = await prisma.institution.findFirst({
      where: { referralCode: code, status: "ACTIVE" },
      select: { name: true },
    });
    if (!referrer) {
      return NextResponse.json({ valid: false, discountPct });
    }
    return NextResponse.json({ valid: true, discountPct, referrerName: referrer.name });
  } catch {
    return NextResponse.json({ valid: false, discountPct: 0 });
  }
}
