import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { requirePageRole, resolveSchoolId } from "@/lib/auth";
import { handleApiError } from "@/lib/api-helpers";
import { generateStudentCode } from "@/lib/constants";

/** معاينة الكود التلقائي القادم للطالب حسب المرحلة والسنة (تسلسل داخل المدرسة) */
export async function GET(req: NextRequest) {
  try {
    const user = await requirePageRole("students", "ADMIN", "STAFF", "ACCOUNTANT", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { searchParams } = new URL(req.url);
    const grade = searchParams.get("grade") || "G1";
    const year = new Date().getFullYear();
    const prefix = `${grade}-${year}-`;
    const lastStudent = await db.student.findFirst({
      where: { studentCode: { startsWith: prefix }, schoolId },
      orderBy: { studentCode: "desc" },
    });
    let sequence = 1;
    if (lastStudent) {
      const lastSeq = parseInt(lastStudent.studentCode.split("-")[2] || "0", 10);
      sequence = lastSeq + 1;
    }
    return NextResponse.json({ code: generateStudentCode(grade, year, sequence) });
  } catch (err) {
    return handleApiError(err);
  }
}
