import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const establishmentId = searchParams.get("establishmentId");
  if (!establishmentId) return NextResponse.json({ error: "Missing establishmentId" }, { status: 400 });

  const classes = await prisma.class.findMany({
    where: { establishmentId },
    include: { _count: { select: { students: true } } },
    orderBy: { createdAt: "desc" },
  });
  return NextResponse.json(classes);
}

export async function POST(req: NextRequest) {
  const body = await req.json();
  const { establishmentId, name, level } = body;
  const cls = await prisma.class.create({
    data: { establishmentId, name, level },
  });
  return NextResponse.json(cls, { status: 201 });
}
