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

type Params = { params: Promise<{ id: string }> };

/** All exam marks of one student, grouped per exam — powers the Academic Transcript. */
export async function GET(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const student = await prisma.student.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true },
  });
  if (!student) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const marks = await prisma.examMark.findMany({
    where: { studentId: student.id },
    select: {
      total: true,
      cq: true,
      mcq: true,
      applied: true,
      examSchedule: {
        select: {
          date: true,
          fullMarks: true,
          totalPassMarks: true,
          subjectItem: { select: { name: true, nameBn: true } },
          exam: {
            select: {
              id: true, name: true, startDate: true, endDate: true,
              classItem: { select: { name: true } },
              sectionItem: { select: { name: true } },
            },
          },
        },
      },
    },
    orderBy: [{ examSchedule: { exam: { startDate: "asc" } } }, { examSchedule: { date: "asc" } }],
  });

  type ExamGroup = {
    exam: { id: number; name: string; className: string | null; sectionName: string | null; startDate: Date; endDate: Date | null };
    rows: { subjectName: string | null; subjectNameBn: string | null; date: Date; fullMarks: number; passMarks: number | null; obtained: number }[];
  };
  const byExam = new Map<number, ExamGroup>();
  for (const m of marks) {
    // obtained: prefer the stored total, else sum whatever parts exist
    const obtained = m.total ?? (m.cq ?? 0) + (m.mcq ?? 0) + (m.applied ?? 0);
    if (obtained === 0 && m.total === null && m.cq === null && m.mcq === null && m.applied === null) continue;
    const e = m.examSchedule.exam;
    let group = byExam.get(e.id);
    if (!group) {
      group = {
        exam: {
          id: e.id, name: e.name,
          className: e.classItem?.name ?? null,
          sectionName: e.sectionItem?.name ?? null,
          startDate: e.startDate,
          endDate: e.endDate,
        },
        rows: [],
      };
      byExam.set(e.id, group);
    }
    group.rows.push({
      subjectName: m.examSchedule.subjectItem?.name ?? null,
      subjectNameBn: m.examSchedule.subjectItem?.nameBn ?? null,
      date: m.examSchedule.date,
      fullMarks: m.examSchedule.fullMarks,
      passMarks: m.examSchedule.totalPassMarks,
      obtained,
    });
  }

  return NextResponse.json({ results: [...byExam.values()] });
}
