import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAnyRole } from "@/lib/auth";

/** Cumulative point table from PUBLISHED results — history tracking.
    Optional ?clubId filters to one club's competitions. */
export async function GET(req: Request) {
  const session = await requireAnyRole(["INSTITUTION_ADMIN", "TEACHER", "STUDENT", "PARENT"]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const clubId = Number(new URL(req.url).searchParams.get("clubId")) || null;

  const results = await prisma.competitionResult.findMany({
    where: {
      publishedAt: { not: null },
      competition: {
        institutionId: session.institutionId,
        ...(clubId ? { clubId } : {}),
      },
    },
    select: {
      points: true,
      rank: true,
      student: { select: { id: true, roll: true, name: true, nameBn: true } },
      competition: { select: { id: true, name: true, clubId: true } },
    },
  });

  const byStudent = new Map<
    number,
    {
      studentId: number;
      roll: string;
      name: string;
      nameBn: string | null;
      points: number;
      wins: number;
      competitions: number;
      history: { competition: string; rank: number; points: number }[];
    }
  >();
  for (const r of results) {
    const s = r.student;
    const row =
      byStudent.get(s.id) ??
      {
        studentId: s.id,
        roll: s.roll,
        name: s.name,
        nameBn: s.nameBn,
        points: 0,
        wins: 0,
        competitions: 0,
        history: [],
      };
    row.points += r.points;
    row.competitions += 1;
    if (r.rank === 1) row.wins += 1;
    row.history.push({ competition: r.competition.name, rank: r.rank, points: r.points });
    byStudent.set(s.id, row);
  }

  const standings = [...byStudent.values()].sort(
    (a, b) => b.points - a.points || a.roll.localeCompare(b.roll)
  );
  return NextResponse.json({ standings });
}
