import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { appBaseUrl } from "@/lib/email-templates";
import { ensureReferralCode, getReferralCommissionPct, getReferralDiscountPct } from "@/lib/referral";

/** Institution portal → referral program info: the institution's own code to
 *  share, the discount it grants, institutions joined with it, whether the
 *  institution itself still has its one-time referral benefit pending, and
 *  the commissions earned when referred institutions take yearly plans. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const code = await ensureReferralCode(session.institutionId);
  const [discountPct, commissionPct, referred, me, commissions] = await Promise.all([
    getReferralDiscountPct(),
    getReferralCommissionPct(),
    prisma.institution.findMany({
      where: { referredById: session.institutionId },
      select: { id: true, name: true, status: true, createdAt: true },
      orderBy: { createdAt: "desc" },
    }),
    prisma.institution.findUnique({
      where: { id: session.institutionId },
      select: { referredById: true, referralDiscountAppliedAt: true, createdAt: true },
    }),
    prisma.referralCommission.findMany({
      where: { ownerInstitutionId: session.institutionId },
      select: {
        id: true,
        pct: true,
        amount: true,
        createdAt: true,
        buyer: { select: { name: true } },
        subscription: { select: { studentRange: true, endDate: true } },
      },
      orderBy: { createdAt: "desc" },
      take: 20,
    }),
  ]);

  const earnedTotal = commissions.reduce((sum, c) => sum + Number(c.amount), 0);

  return NextResponse.json({
    code,
    shareUrl: `${appBaseUrl()}/register?ref=${code}`,
    discountPct,
    commissionPct,
    referredCount: referred.length,
    referredInstitutions: referred.map((r) => ({
      id: r.id,
      name: r.name,
      status: r.status,
      createdAt: r.createdAt,
    })),
    // my own benefit: registered via a referral code and not yet consumed
    discountPending: Boolean(me?.referredById) && !me?.referralDiscountAppliedAt,
    // owner earnings: 10% (configurable) of each referred institution's
    // total yearly amount, paid out by the Increlog team
    earnedTotal,
    commissions: commissions.map((c) => ({
      id: c.id,
      buyerName: c.buyer.name,
      pct: Number(c.pct),
      amount: Number(c.amount),
      studentRange: c.subscription.studentRange,
      createdAt: c.createdAt,
    })),
  });
}
