// Permission definitions: resource:action naming convention
// Used by requirePermission() on server and usePermission() on client

/**
 * All role names recognized by the system.
 * Used to type-check `AuthContext.roles`, `ROLE_PERMISSIONS` keys, and JWT/session payloads.
 */
export type Role =
  | "admin"
  | "teacher"
  | "student"
  | "parent"
  | "grade_head"
  | "teaching_head"

export const Permissions = {
  // Exam
  EXAM_CREATE: "exam:create",
  EXAM_READ: "exam:read",
  EXAM_UPDATE: "exam:update",
  EXAM_DELETE: "exam:delete",
  EXAM_DUPLICATE: "exam:duplicate",
  EXAM_PUBLISH: "exam:publish",
  EXAM_AI_GENERATE: "exam:ai_generate",
  EXAM_SUBMIT: "exam:submit",

  // Homework
  HOMEWORK_CREATE: "homework:create",
  HOMEWORK_GRADE: "homework:grade",
  HOMEWORK_SUBMIT: "homework:submit",

  // Question
  QUESTION_CREATE: "question:create",
  QUESTION_READ: "question:read",
  QUESTION_UPDATE: "question:update",
  QUESTION_DELETE: "question:delete",

  // Textbook
  TEXTBOOK_CREATE: "textbook:create",
  TEXTBOOK_READ: "textbook:read",
  TEXTBOOK_UPDATE: "textbook:update",
  TEXTBOOK_DELETE: "textbook:delete",

  // Class
  CLASS_CREATE: "class:create",
  CLASS_READ: "class:read",
  CLASS_UPDATE: "class:update",
  CLASS_DELETE: "class:delete",
  CLASS_ENROLL: "class:enroll",
  CLASS_SCHEDULE: "class:schedule",

  // School management
  SCHOOL_MANAGE: "school:manage",
  GRADE_MANAGE: "grade:manage",
  USER_MANAGE: "user:manage",

  // User (self-service)
  /** Self-service profile update (all authenticated roles) */
  USER_PROFILE_UPDATE: "user:profile_update",

  // AI
  AI_CHAT: "ai:chat",
  AI_CONFIGURE: "ai:configure",

  // Settings
  SETTINGS_ADMIN: "settings:admin",

  // Audit
  AUDIT_LOG_READ: "audit_log:read",

  // Announcement
  ANNOUNCEMENT_MANAGE: "announcement:manage",
  ANNOUNCEMENT_READ: "announcement:read",

  // Grade Record (成绩录入与查询)
  GRADE_RECORD_MANAGE: "grade_record:manage",
  GRADE_RECORD_READ: "grade_record:read",

  // File (文件上传与管理)
  FILE_UPLOAD: "file:upload",
  FILE_READ: "file:read",
  FILE_DELETE: "file:delete",

  // Course Plan (课程计划管理)
  COURSE_PLAN_MANAGE: "course_plan:manage",
  COURSE_PLAN_READ: "course_plan:read",

  // Attendance (考勤管理)
  ATTENDANCE_MANAGE: "attendance:manage",
  ATTENDANCE_READ: "attendance:read",

  // Message (站内消息)
  MESSAGE_SEND: "message:send",
  MESSAGE_READ: "message:read",
  MESSAGE_DELETE: "message:delete",

  // Scheduling (排课与调课)
  SCHEDULE_AUTO: "schedule:auto",
  SCHEDULE_ADJUST: "schedule:adjust",

  // P2: Elective Course (选课管理)
  ELECTIVE_MANAGE: "elective:manage",
  ELECTIVE_READ: "elective:read",
  ELECTIVE_SELECT: "elective:select",

  // P2: Exam Proctoring (考试监考)
  EXAM_PROCTOR: "exam:proctor",
  EXAM_PROCTOR_READ: "exam:proctor:read",

  // P2: Learning Diagnostic (学情诊断)
  DIAGNOSTIC_MANAGE: "diagnostic:manage",
  DIAGNOSTIC_READ: "diagnostic:read",

  // Lesson Plan (备课)
  LESSON_PLAN_CREATE: "lesson_plan:create",
  LESSON_PLAN_READ: "lesson_plan:read",
  LESSON_PLAN_UPDATE: "lesson_plan:update",
  LESSON_PLAN_DELETE: "lesson_plan:delete",
  LESSON_PLAN_PUBLISH: "lesson_plan:publish",

  // Dashboard (仪表盘 — 各角色独立读权限)
  DASHBOARD_ADMIN_READ: "dashboard:admin_read",
  DASHBOARD_TEACHER_READ: "dashboard:teacher_read",
  DASHBOARD_STUDENT_READ: "dashboard:student_read",
  DASHBOARD_PARENT_READ: "dashboard:parent_read",
} as const satisfies Record<string, string>

export type Permission = (typeof Permissions)[keyof typeof Permissions]

const VALID_ROLES: readonly Role[] = [
  "admin",
  "teacher",
  "student",
  "parent",
  "grade_head",
  "teaching_head",
]

/**
 * Type guard: narrows `string` to `Role`.
 * Use to filter role names coming from the DB or external sources.
 */
export function isRole(value: string): value is Role {
  return (VALID_ROLES as readonly string[]).includes(value)
}

/**
 * Data scope for row-level security.
 *
 * Determines which rows a user is allowed to see based on their role:
 * - `all`: no filtering (admin).
 * - `owned`: only rows created by the user.
 * - `class_members`: rows visible to members of the user's enrolled classes (student).
 *    `classIds` is pre-resolved by `resolveDataScope` to avoid N+1 queries downstream.
 * - `grade_managed`: rows within grades the user manages (grade_head / teaching_head).
 * - `class_taught`: rows within classes the user teaches (teacher).
 * - `children`: rows belonging to the user's children (parent).
 */
export type DataScope =
  | { type: "all" }
  | { type: "owned"; userId: string }
  | { type: "class_members"; classIds: string[] }
  | { type: "grade_managed"; gradeIds: string[] }
  | { type: "class_taught"; classIds: string[]; subjectIds?: string[] }
  | { type: "children"; childrenIds: string[] }

/**
 * Authentication context for the current request.
 *
 * - `userId`: the authenticated user's id.
 * - `roles`: all role names assigned to the user (typed as `Role[]` to catch typos at compile time).
 * - `permissions`: the merged set of permission strings granted to the user.
 * - `dataScope`: the row-level security scope used to filter queries.
 */
export interface AuthContext {
  userId: string
  roles: Role[]
  permissions: Permission[]
  dataScope: DataScope
}
