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

/** The caller's own (child's) student profile — for the self-service page. */
export async function GET() {
  const session = await requireAnyRole(["STUDENT", "PARENT"]);
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const me = await prisma.user.findUnique({ where: { id: session.userId } });
  const studentId = session.role === "STUDENT" ? me?.studentProfileId : me?.parentOfStudentId;
  if (!studentId) {
    return NextResponse.json({ student: null });
  }

  // branding for printable documents (ID card, marksheet, receipts)
  const institution = await prisma.institution.findUnique({
    where: { id: session.institutionId! },
    select: { name: true, address: true, phone: true, website: true, logo: true },
  });

  const student = await prisma.student.findUnique({
    where: { id: studentId },
    select: {
      id: true,
      roll: true,
      registrationNo: true,
      cardNo: true,
      cardIssuedAt: true,
      cardValidTill: true,
      bloodGroup: true,
      name: true,
      nameBn: true,
      gender: true,
      dob: true,
      guardianName: true,
      guardianNameBn: true,
      guardianPhone: true,
      motherName: true,
      motherNameBn: true,
      address: true,
      photoUrl: true,
      classItemId: true,
      classItem: { select: { name: true, nameBn: true } },
      sectionItem: { select: { name: true, nameBn: true } },
      optionalSubjects: {
        include: { subjectItem: { select: { id: true, name: true, nameBn: true } } },
      },
    },
  });

  return NextResponse.json({
    student: student
      ? {
          ...student,
          className: student.classItem?.name ?? null,
          classNameBn: student.classItem?.nameBn ?? null,
          sectionName: student.sectionItem?.name ?? null,
          sectionNameBn: student.sectionItem?.nameBn ?? null,
          classItem: undefined,
          sectionItem: undefined,
          optionalSubjects: student.optionalSubjects.map((o) => o.subjectItem),
        }
      : null,
    institution: institution ?? null,
  });
}
