import "server-only"

import { eq, inArray, sql, type SQL } from "drizzle-orm"

import { gradeRecords } from "@/shared/db/schema"
import { getClassIdsByGradeIdsSubquery } from "@/modules/classes/data-access"
import type { DataScope } from "@/shared/types/permissions"

/**
 * Build a Drizzle SQL filter that restricts `gradeRecords` rows based on
 * the current user's DataScope. Returns `null` when no row-level filter
 * is required (e.g. admin scope).
 *
 * @param scope  Current user's DataScope
 * @param currentUserId  Current user's id (required for `class_members` scope
 *   to filter by the student's own records; ignored for other scopes)
 */
export const buildScopeClassFilter = (
  scope: DataScope,
  currentUserId?: string
): SQL | null => {
  if (scope.type === "all") return null
  if (scope.type === "class_taught") {
    return scope.classIds.length > 0
      ? inArray(gradeRecords.classId, scope.classIds)
      : sql`1=0`
  }
  if (scope.type === "grade_managed") {
    // P2-4 修复：grade_managed scope 应返回所管年级的班级成绩记录
    // P2-2 修复：通过 classes data-access 提供的子查询函数构建 SQL，不直接查询 classes 表
    return scope.gradeIds.length > 0
      ? inArray(
          gradeRecords.classId,
          getClassIdsByGradeIdsSubquery(scope.gradeIds)
        )
      : sql`1=0`
  }
  if (scope.type === "class_members") {
    // P3 修复：class_members scope 内置 studentId 条件，避免调用方遗漏
    return currentUserId
      ? eq(gradeRecords.studentId, currentUserId)
      : sql`1=0`
  }
  if (scope.type === "children") {
    return scope.childrenIds.length > 0
      ? inArray(gradeRecords.studentId, scope.childrenIds)
      : sql`1=0`
  }
  if (scope.type === "owned") return eq(gradeRecords.studentId, scope.userId)
  return sql`1=0`
}
