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

export async function GET(request: NextRequest) {
  try {
    const token = getTokenFromRequest(request);
    if (!token) return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 });
    const payload = verifyToken(token);

    // Ensure only Siswa or Admin can access (or maybe Parents later)
    if (!payload || payload.role !== "SISWA") {
      // If needed, allow parent
      if (payload?.role !== "ADMIN")
        return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 });
    }

    const siswa = await prisma.siswa.findUnique({
      where: { userId: payload.userId },
      select: { id: true },
    });

    if (!siswa) return NextResponse.json({ success: false, message: "Siswa not found" }, { status: 404 });

    const grades = await prisma.nilaiHarian.findMany({
      where: { siswaId: siswa.id },
      include: {
        penilaianHarian: {
          include: {
            mapel: true,
            guru: { select: { nama: true } },
          },
        },
      },
      orderBy: { penilaianHarian: { tanggal: "desc" } },
    });

    return NextResponse.json({ success: true, data: grades });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ success: false, message: "Error" }, { status: 500 });
  }
}
