import { db } from "@/lib/db";
import { GRADES } from "@/lib/constants";

/** التحقق من صلاحية كود الصف الدراسي (ثابت في النظام أو مخصص أضافه المدير وغير مخفي) — داخل نطاق المدرسة */
export async function isValidGradeCode(code: string, schoolId?: string | null): Promise<boolean> {
  const isBuiltIn = GRADES.some((g) => g.code === code);
  if (!isBuiltIn) {
    const custom = await db.customGrade.findFirst({
      where: { code, schoolId: schoolId ?? undefined },
    });
    if (!custom) return false;
  }
  if (schoolId) {
    const hidden = await db.hiddenGrade.findUnique({
      where: { code_schoolId: { code, schoolId } },
    });
    if (hidden) return false;
  } else {
    const hidden = await db.hiddenGrade.findFirst({ where: { code } });
    if (hidden) return false;
  }
  return true;
}

/** مسميات الصفوف المخصصة كخريطة code -> nameAr (داخل نطاق المدرسة) */
export async function getCustomGradeLabels(schoolId?: string | null): Promise<Record<string, string>> {
  const rows = await db.customGrade.findMany({
    where: { schoolId: schoolId ?? undefined },
  });
  const map: Record<string, string> = {};
  for (const r of rows) map[r.code] = r.nameAr;
  return map;
}

/** أكواد الصفوف الأساسية المخفية من قبل المدير (داخل نطاق المدرسة) */
export async function getHiddenGradeCodes(schoolId?: string | null): Promise<string[]> {
  const rows = await db.hiddenGrade.findMany({
    where: { schoolId: schoolId ?? undefined },
  });
  return rows.map((r) => r.code);
}
