import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { PRICING_CATEGORIES } from "@/lib/pricing";

/** Public: landing-page pricing cards — every category that has active
 *  student-count slabs, with its tiers sorted by range. */

export async function GET() {
  const tiers = await prisma.pricingTier.findMany({
    where: { active: true },
    orderBy: [{ category: "asc" }, { minStudents: "asc" }],
  });

  const byCategory = new Map<string, typeof tiers>();
  for (const tier of tiers) {
    const list = byCategory.get(tier.category) ?? [];
    list.push(tier);
    byCategory.set(tier.category, list);
  }

  const categories = PRICING_CATEGORIES.filter((c) => byCategory.has(c.code)).map((c) => ({
    ...c,
    tiers: byCategory.get(c.code)!.map((t) => ({
      id: t.id,
      minStudents: t.minStudents,
      maxStudents: t.maxStudents,
      monthlyPrice: Number(t.monthlyPrice),
      yearlyDiscount: Number(t.yearlyDiscount),
    })),
  }));

  return NextResponse.json({ categories });
}
