/**
 * student-portal GraphQL 类型定义（ai14）
 *
 * 对齐 student-bff GraphQL schema（ARB-001 ActionState 信封）。
 * 所有 GraphQL 操作的响应均包裹在 ActionState<T> 信封中：
 *   { success, errors, data, extensions }
 * Hook 层负责解包并提取 data 字段。
 *
 * 错误码前缀（known-issues §2.15）：
 * - IAM_*：iam 服务
 * - CORE_EDU_*：core-edu 服务（考试/作业/成绩/考勤统一前缀）
 * - BFF_STUDENT_*：student-bff 聚合层
 * - GW_*：api-gateway
 */

// ---------------------------------------------------------------------------
// ActionState 信封类型（ARB-001 §1.3 + 总裁裁决 §3.4 方案 B 降级模式）
// ---------------------------------------------------------------------------

/** ActionState 错误项 */
export interface ActionError {
  /** 错误码，前缀标识来源服务（如 BFF_STUDENT_UPSTREAM_UNAVAILABLE） */
  code: string;
  /** 人类可读消息（已 i18n 路由，前端可直接展示） */
  message: string;
  /** 关联字段（如校验错误指向具体输入字段） */
  field?: string;
  /** 额外详情（结构化，按 code 解析） */
  details?: unknown;
}

/** ActionState 降级扩展（§3.4 方案 B） */
export interface ActionExtensions {
  /** 降级模式标记：部分上游不可用时返回部分数据 */
  degraded?: boolean;
  /** 降级原因说明 */
  degradedReason?: string;
  /** 部分聚合失败标记 */
  partial?: boolean;
  /** 链路追踪 ID */
  traceId?: string;
}

/** ActionState 统一响应信封 */
export interface ActionState<T> {
  /** 操作是否成功 */
  success: boolean;
  /** 错误列表（成功时空数组） */
  errors: ActionError[];
  /** 业务数据（失败时为 null） */
  data: T | null;
  /** 扩展信息（降级标记等） */
  extensions?: ActionExtensions;
}

// ---------------------------------------------------------------------------
// 通用领域类型
// ---------------------------------------------------------------------------

/** 学科引用 */
export interface SubjectRef {
  id: string;
  name: string;
}

/** 考试状态 */
export type ExamStatus =
  "not_started" | "in_progress" | "submitted" | "graded" | "expired";

/** 作业状态 */
export type HomeworkStatus = "pending" | "submitted" | "graded" | "overdue";

/** 出勤状态 */
export type AttendanceStatus = "present" | "absent" | "late";

/** 通知类型 */
export type NotificationType = "homework" | "exam" | "grade" | "system";

/** 题目类型 */
export type QuestionType =
  "single-choice" | "multiple-choice" | "fill-blank" | "short-answer" | "essay";

/** 学习路径节点状态 */
export type LearningPathStatus =
  "locked" | "available" | "in-progress" | "completed";

/** 推荐动作 */
export type RecommendedAction = "review" | "practice" | "mastered";

/** 数据范围（学生固定 L0） */
export type DataScope = "L0" | "L1" | "L2" | "L3" | "L4" | "L5";

// ---------------------------------------------------------------------------
// 实体类型（与 fixture JSON 对齐）
// ---------------------------------------------------------------------------

/** 当前学生信息（currentUser 响应数据） */
export interface CurrentUser {
  id: string;
  name: string;
  studentNo: string;
  grade: string;
  avatar: string | null;
  roles: string[];
  permissions: string[];
  dataScope: DataScope;
}

/** 班级信息 */
export interface ClassInfo {
  id: string;
  name: string;
  homeroomTeacher: string;
  studentCount: number;
  grade: string;
  year: number;
}

/** 考试列表项 */
export interface ExamListItem {
  id: string;
  name: string;
  subject: SubjectRef;
  status: ExamStatus;
  startsAt: string;
  expiresAt: string;
  durationSeconds: number;
  questionCount: number;
  totalScore: number;
  /** 已提交时携带 */
  submittedAt?: string;
  submissionId?: string;
}

/** 题目选项 */
export interface QuestionOption {
  id: string;
  text: string;
}

/** 题目 */
export interface ExamQuestion {
  id: string;
  type: QuestionType;
  content: string;
  options: QuestionOption[];
  score: number;
  maxScore: number;
}

/** 考试详情（含题目） */
export interface ExamDetail {
  id: string;
  name: string;
  subject: SubjectRef;
  status: ExamStatus;
  startsAt: string;
  expiresAt: string;
  durationSeconds: number;
  totalScore: number;
  questionCount: number;
  questions: ExamQuestion[];
}

/** 作业列表项 */
export interface HomeworkListItem {
  id: string;
  title: string;
  subject: SubjectRef;
  status: HomeworkStatus;
  dueAt: string;
  assignedAt: string;
  questionCount: number;
  totalScore: number;
  submittedAt?: string;
  gradedAt?: string;
  score?: number;
}

/** 作业题目 */
export interface HomeworkQuestion {
  id: string;
  type: QuestionType;
  content: string;
  options: QuestionOption[];
  maxScore: number;
}

/** 作业详情（含题目） */
export interface HomeworkDetail {
  id: string;
  title: string;
  subject: SubjectRef;
  status: HomeworkStatus;
  dueAt: string;
  assignedAt: string;
  questionCount: number;
  totalScore: number;
  questions: HomeworkQuestion[];
}

/** 成绩记录 */
export interface GradeRecord {
  id: string;
  examId: string;
  examName: string;
  subject: SubjectRef;
  score: number;
  maxScore: number;
  grade: string;
  rank: number;
  submittedAt: string;
  gradedAt: string;
}

/** 考勤记录 */
export interface AttendanceRecord {
  id: string;
  date: string;
  status: AttendanceStatus;
  subject: SubjectRef;
  /** 迟到时携带的迟到分钟数 */
  lateMinutes?: number;
  /** 缺勤原因 */
  reason?: string;
}

/** 教材 */
export interface Textbook {
  id: string;
  name: string;
  subject: SubjectRef;
  version: string;
  author: string;
}

/** 章节节点（树形结构，3 级） */
export interface ChapterNode {
  id: string;
  textbookId: string;
  name: string;
  level: 1 | 2 | 3;
  parentId: string | null;
  order: number;
  children: ChapterNode[];
}

/** 学习路径节点 */
export interface LearningPathNode {
  id: string;
  name: string;
  knowledgePointId: string;
  status: LearningPathStatus;
  mastery: number;
  dependencies: string[];
  recommendedOrder: number;
}

/** 仪表盘即将到期的作业 */
export interface DashboardHomework {
  id: string;
  title: string;
  dueAt: string;
  subject: SubjectRef;
  status: HomeworkStatus;
}

/** 仪表盘即将到来的考试 */
export interface DashboardExam {
  id: string;
  name: string;
  startsAt: string;
  expiresAt: string;
  durationSeconds: number;
  subject: SubjectRef;
  status: ExamStatus;
}

/** 仪表盘近期成绩 */
export interface DashboardGrade {
  id: string;
  examName: string;
  score: number;
  maxScore: number;
  grade: string;
  submittedAt: string;
}

/** 学生仪表盘聚合数据 */
export interface StudentDashboard {
  upcomingHomework: DashboardHomework[];
  upcomingExams: DashboardExam[];
  recentGrades: DashboardGrade[];
  attendanceRate: number;
  learningStreakDays: number;
  avgScore: number;
  classRank: number;
}

/** 薄弱点（错题本） */
export interface WeaknessPoint {
  id: string;
  questionId: string;
  questionContent: string;
  subject: SubjectRef;
  knowledgePointId: string;
  knowledgePointName: string;
  mastery: number;
  wrongCount: number;
  lastWrongAt: string;
  recommendedAction: RecommendedAction;
}

/** 学习趋势数据点 */
export interface TrendDataPoint {
  date: string;
  score: number;
  examName: string;
}

/** 通知项 */
export interface NotificationItem {
  id: string;
  type: NotificationType;
  title: string;
  content: string;
  read: boolean;
  createdAt: string;
}

/** 服务器时间 */
export interface ServerTime {
  /** ISO 8601 UTC 时间戳 */
  timestamp: string;
  /** 服务器与客户端时间偏移（秒） */
  offset: number;
}

// ---------------------------------------------------------------------------
// 扩展实体类型（4 查询 + 5 变更）
// ---------------------------------------------------------------------------

/** 课表项（周视图） */
export interface ScheduleItem {
  id: string;
  /** 0=周日, 1=周一, ..., 6=周六 */
  dayOfWeek: number;
  /** "08:00" */
  startTime: string;
  /** "08:45" */
  endTime: string;
  subject: string;
  teacher: string;
  classroom: string;
}

/** 成长曲线数据点（myScore vs classAverage） */
export interface GrowthDataPoint {
  date: string;
  myScore: number;
  classAverage: number;
}

/** 作业分析题目项 */
export interface AssignmentAnalysisQuestion {
  questionId: string;
  questionText: string;
  questionType: string;
  correctRate: number;
  referenceAnswer: string;
  knowledgePoints: string[];
}

/** 作业分析结果 */
export interface AssignmentAnalysis {
  homeworkId: string;
  title: string;
  totalScore: number;
  avgScore: number;
  maxScore: number;
  minScore: number;
  submitCount: number;
  questions: AssignmentAnalysisQuestion[];
}

/** 学生个人资料 */
export interface StudentProfile {
  id: string;
  name: string;
  studentNo: string;
  email: string;
  phone: string;
  gender: string;
  avatar: string;
  grade: string;
  classId: string;
  className: string;
  bio: string;
  preferredSubjectId: string;
}

// ---------------------------------------------------------------------------
// 批次 A 扩展实体类型
// ---------------------------------------------------------------------------

/** 错题来源类型 */
export type ErrorBookSourceType = "exam" | "homework" | "manual";

/** 错题状态 */
export type ErrorBookStatus = "new" | "learning" | "mastered" | "archived";

/** 错题本条目 */
export interface ErrorBookItem {
  id: string;
  questionId: string;
  questionContent: string;
  sourceType: ErrorBookSourceType;
  subject: SubjectRef;
  knowledgePointIds: string[];
  knowledgePointName: string;
  status: ErrorBookStatus;
  /** 掌握度 0-1 */
  masteryLevel: number;
  nextReviewAt: string | null;
  reviewCount: number;
  correctStreak: number;
  note: string | null;
  errorTags: string[];
  createdAt: string;
  updatedAt: string;
}

/** 错题本统计 */
export interface ErrorBookStats {
  totalCount: number;
  newCount: number;
  learningCount: number;
  masteredCount: number;
  dueReviewCount: number;
  /** 掌握率 0-1 */
  masteredRate: number;
}

/** 错题本响应数据 */
export interface ErrorBookData {
  items: ErrorBookItem[];
  stats: ErrorBookStats;
}

/** 请假类型 */
export type LeaveType = "sick" | "personal" | "family" | "other";

/** 请假状态 */
export type LeaveStatus = "pending" | "approved" | "rejected" | "cancelled";

/** 请假记录 */
export interface LeaveRequest {
  id: string;
  leaveType: LeaveType;
  startDate: string;
  endDate: string;
  reason: string;
  status: LeaveStatus;
  reviewComment: string | null;
  reviewedAt: string | null;
  reviewerName: string | null;
  className: string;
  attendanceSynced: boolean;
  createdAt: string;
}

/** 选课课程状态 */
export type ElectiveCourseStatus =
  | "draft"
  | "open"
  | "closed"
  | "cancelled";

/** 选课模式 */
export type ElectiveSelectionMode = "fcfs" | "lottery";

/** 选课记录状态 */
export type CourseSelectionStatus =
  | "selected"
  | "enrolled"
  | "waitlist"
  | "dropped"
  | "rejected";

/** 选课课程（列表/详情） */
export interface ElectiveCourse {
  id: string;
  name: string;
  teacherName: string | null;
  subjectName: string | null;
  gradeName: string | null;
  description: string | null;
  capacity: number;
  enrolledCount: number;
  classroom: string | null;
  schedule: string | null;
  startDate: string | null;
  endDate: string | null;
  selectionStartAt: string | null;
  selectionEndAt: string | null;
  dropDeadline: string | null;
  status: ElectiveCourseStatus;
  selectionMode: ElectiveSelectionMode;
  credit: string;
}

/** 我的选课记录（含课程信息） */
export interface CourseSelection {
  id: string;
  courseId: string;
  courseName: string;
  status: CourseSelectionStatus;
  selectedAt: string;
  enrolledAt: string | null;
  droppedAt: string | null;
  dropReason: string | null;
  course: {
    id: string;
    name: string;
    teacherName: string | null;
    subjectName: string | null;
    capacity: number;
    enrolledCount: number;
    classroom: string | null;
    schedule: string | null;
    credit: string;
    status: ElectiveCourseStatus;
  };
}

/** 练习类型 */
export type PracticeType =
  | "error_variant"
  | "knowledge_point"
  | "weak_chapter"
  | "ai_recommended";

/** 练习状态 */
export type PracticeStatus = "in_progress" | "completed" | "abandoned";

/** 练习答题状态 */
export type PracticeAnswerStatus = "pending" | "answered" | "skipped";

/** 练习会话摘要 */
export interface PracticeSessionSummary {
  id: string;
  practiceType: PracticeType;
  status: PracticeStatus;
  totalQuestions: number;
  answeredQuestions: number;
  correctCount: number;
  /** 正确率 0-1 */
  accuracy: number;
  startedAt: string;
  completedAt: string | null;
}

/** 练习统计 */
export interface PracticeStats {
  totalSessions: number;
  completedSessions: number;
  totalQuestionsAnswered: number;
  totalCorrect: number;
  /** 总体正确率 0-1 */
  overallAccuracy: number;
}

/** 我的练习会话响应数据 */
export interface MyPracticeSessionsData {
  sessions: PracticeSessionSummary[];
  stats: PracticeStats;
}

/** 练习题目选项 */
export interface PracticeQuestionOption {
  id: string;
  text: string;
}

/** 练习题目 */
export interface PracticeQuestion {
  id: string;
  questionId: string;
  content: string;
  type: string;
  options: PracticeQuestionOption[];
  maxScore: number;
  status: PracticeAnswerStatus;
}

/** 练习会话详情（启动后） */
export interface PracticeSessionDetail {
  session: {
    id: string;
    practiceType: PracticeType;
    status: PracticeStatus;
    totalQuestions: number;
    answeredQuestions: number;
    correctCount: number;
    accuracy: number;
    startedAt: string;
    currentQuestionIndex: number;
    questions: PracticeQuestion[];
  };
}

/** 提交练习答题响应 */
export interface SubmitPracticeAnswerResult {
  answerId: string;
  isCorrect: boolean;
  score: number;
  maxScore: number;
  correctAnswer: string;
  sessionCompleted: boolean;
  session: {
    id: string;
    answeredQuestions: number;
    correctCount: number;
    accuracy: number;
    status: PracticeStatus;
  };
}

/** 公告类型 */
export type AnnouncementType = "school" | "grade" | "class";

/** 公告状态 */
export type AnnouncementStatus = "draft" | "published" | "archived";

/** 公告 */
export interface Announcement {
  id: string;
  title: string;
  content: string;
  type: AnnouncementType;
  status: AnnouncementStatus;
  authorName: string | null;
  publishedAt: string | null;
  isPinned: boolean;
  isReadByCurrentUser: boolean;
  createdAt: string;
  updatedAt?: string;
}

/** 课案内容（只读视图） */
export interface LessonPlanContent {
  objectives: string | null;
  keyPoints: string | null;
  summary: string | null;
  homework: string | null;
  blackboard: string | null;
}

/** 课案列表项 */
export interface LessonPlanListItem {
  id: string;
  title: string;
  subjectName: string | null;
  gradeName: string | null;
  chapterTitle: string | null;
  creatorName: string | null;
  status: string;
  publishedAt: string | null;
  updatedAt: string;
}

/** 课案详情 */
export interface LessonPlanDetail {
  id: string;
  title: string;
  subjectName: string | null;
  gradeName: string | null;
  chapterTitle: string | null;
  creatorName: string | null;
  status: string;
  content: LessonPlanContent;
  publishedAt: string | null;
  updatedAt: string;
}

/** 课程计划状态 */
export type CoursePlanStatus =
  | "planning"
  | "active"
  | "completed"
  | "paused";

/** 课程计划学期 */
export type CoursePlanSemester = "1" | "2";

/** 课程计划列表项 */
export interface CoursePlanListItem {
  id: string;
  className: string | null;
  subjectName: string | null;
  teacherName: string | null;
  semester: CoursePlanSemester;
  totalHours: number;
  completedHours: number;
  weeklyHours: number;
  startDate: string | null;
  endDate: string | null;
  syllabus: string | null;
  objectives: string | null;
  status: CoursePlanStatus;
}

/** 课程计划周次条目 */
export interface CoursePlanItem {
  id: string;
  week: number;
  topic: string;
  content: string | null;
  hours: number;
  textbookChapter: string | null;
  notes: string | null;
  isCompleted: boolean;
  completedAt: string | null;
}

/** 课程计划详情（含周次条目） */
export interface CoursePlanDetail extends CoursePlanListItem {
  items: CoursePlanItem[];
}

/** 报告卡成绩记录 */
export interface ReportCardRecord {
  id: string;
  examName: string;
  score: number;
  maxScore: number;
  grade: string;
  rank: number;
  submittedAt: string;
}

/** 报告卡学科项 */
export interface ReportCardSubjectItem {
  subjectId: string;
  subjectName: string;
  averageScore: number;
  rankInSubject: number;
  totalStudentsInSubject: number;
  fullScoreTotal: number;
  records: ReportCardRecord[];
}

/** 成绩报告卡 */
export interface ReportCardData {
  studentId: string;
  studentName: string;
  classId: string;
  className: string;
  classTeacherName: string;
  academicYearName: string | null;
  semester: string;
  subjects: ReportCardSubjectItem[];
  overallAverage: number;
  overallRank: number;
  classTotalStudents: number;
  overallPassRate: number;
  overallExcellentRate: number;
  generatedAt: string;
}

/** 诊断报告类型 */
export type DiagnosticReportType = "individual" | "class" | "grade";

/** 诊断报告状态 */
export type DiagnosticReportStatus = "draft" | "published" | "archived";

/** 置信度等级 */
export type ConfidenceLevel = "low" | "medium" | "high";

/** 诊断报告 */
export interface DiagnosticReport {
  id: string;
  reportType: DiagnosticReportType;
  period: string | null;
  summary: string | null;
  strengths: string[] | null;
  weaknesses: string[] | null;
  recommendations: string[] | null;
  overallScore: number | null;
  status: DiagnosticReportStatus;
  createdAt: string;
}

/** 掌握度条目 */
export interface MasteryItem {
  knowledgePointId: string;
  knowledgePointName: string;
  /** 0-100 */
  masteryLevel: number;
  totalQuestions: number;
  correctQuestions: number;
  lastAssessedAt: string;
}

/** 掌握度摘要 */
export interface MasterySummary {
  studentId: string;
  studentName: string;
  averageMastery: number;
  totalKnowledgePoints: number;
  confidenceLevel: ConfidenceLevel;
  mastery: MasteryItem[];
}

// ---------------------------------------------------------------------------
// Mutation 输入类型
// ---------------------------------------------------------------------------

/** 答案输入（联合类型，按题型区分） */
export type AnswerInput =
  | { type: "single-choice"; optionId: string }
  | { type: "multiple-choice"; optionIds: string[] }
  | { type: "fill-blank"; values: string[] }
  | { type: "short-answer"; text: string }
  | { type: "essay"; text: string; attachments?: string[] };

/** 提交作业输入 */
export interface SubmitHomeworkInput {
  homeworkId: string;
  answers: Array<{ questionId: string; answer: AnswerInput }>;
  note?: string;
}

/** 提交考试输入 */
export interface SubmitExamInput {
  examId: string;
  answers: Array<{ questionId: string; answer: AnswerInput }>;
}

/** 保存考试草稿输入 */
export interface SaveExamDraftInput {
  examId: string;
  questionId: string;
  answer: AnswerInput;
}

/** 标记已读输入 */
export interface MarkAsReadInput {
  notificationId: string;
}

/** 批量标记已读输入 */
export interface MarkAllAsReadInput {
  type?: NotificationType;
}

/** 记录考试违规输入 */
export interface RecordExamViolationInput {
  examId: string;
  violationType:
    | "tab-switch"
    | "copy-paste"
    | "fullscreen-exit"
    | "multi-tab"
    | "window-blur";
  timestamp: string;
  duration?: number;
  details?: string;
}

/** 记录粘贴事件输入 */
export interface RecordPasteEventInput {
  examId: string;
  questionId: string;
  timestamp: string;
}

/** 更新通知偏好输入 */
export interface UpdateNotificationPreferenceInput {
  type: NotificationType;
  enabled: boolean;
}

// ---------------------------------------------------------------------------
// 扩展 Mutation 输入类型
// ---------------------------------------------------------------------------

/** 更新个人资料输入 */
export interface UpdateProfileInput {
  name?: string;
  email?: string;
  phone?: string;
  gender?: string;
  bio?: string;
  preferredSubjectId?: string;
}

/** 修改密码输入 */
export interface ChangePasswordInput {
  currentPassword: string;
  newPassword: string;
}

/** 作业延期申请输入 */
export interface RequestExtensionInput {
  homeworkId: string;
  reason: string;
}

/** 加入班级输入 */
export interface JoinClassInput {
  inviteCode: string;
}

/** 退出班级输入 */
export interface LeaveClassInput {
  classId: string;
}

// ---------------------------------------------------------------------------
// 批次 A 扩展 Mutation 输入类型
// ---------------------------------------------------------------------------

/** 添加错题输入 */
export interface AddErrorBookItemInput {
  questionId: string;
  questionContent: string;
  sourceType: ErrorBookSourceType;
  subjectId: string;
  knowledgePointIds?: string[];
  knowledgePointName?: string;
  note?: string;
  errorTags?: string[];
}

/** 更新错题输入（含复习自评） */
export interface UpdateErrorBookItemInput {
  id: string;
  status?: ErrorBookStatus;
  reviewResult?: "again" | "hard" | "good" | "easy";
  note?: string;
}

/** 删除错题输入 */
export interface DeleteErrorBookItemInput {
  id: string;
}

/** 创建请假申请输入 */
export interface CreateLeaveRequestInput {
  leaveType: LeaveType;
  startDate: string;
  endDate: string;
  reason: string;
}

/** 撤销请假申请输入 */
export interface CancelLeaveRequestInput {
  id: string;
}

/** 选课输入 */
export interface SelectElectiveCourseInput {
  courseId: string;
}

/** 退选输入 */
export interface DropElectiveCourseInput {
  courseId: string;
  dropReason?: string;
}

/** 启动练习会话输入 */
export interface StartPracticeSessionInput {
  practiceType: PracticeType;
  subjectId?: string;
  knowledgePointIds?: string[];
  questionCount?: number;
}

/** 提交练习答题输入 */
export interface SubmitPracticeAnswerInput {
  sessionId: string;
  questionId: string;
  answer: string;
}

/** 标记公告已读输入 */
export interface MarkAnnouncementReadInput {
  announcementId: string;
}

// ---------------------------------------------------------------------------
// 批次 A 扩展 Mutation 响应数据类型
// ---------------------------------------------------------------------------

/** 添加错题响应 */
export interface AddErrorBookItemResult {
  id: string;
  status: ErrorBookStatus;
  createdAt: string;
}

/** 更新错题响应 */
export interface UpdateErrorBookItemResult {
  id: string;
  status: ErrorBookStatus;
  masteryLevel: number;
  nextReviewAt: string | null;
  reviewCount: number;
}

/** 删除错题响应 */
export interface DeleteErrorBookItemResult {
  id: string;
  deleted: boolean;
}

/** 创建请假响应 */
export interface CreateLeaveRequestResult {
  id: string;
  status: LeaveStatus;
  createdAt: string;
}

/** 撤销请假响应 */
export interface CancelLeaveRequestResult {
  id: string;
  status: LeaveStatus;
}

/** 选课响应 */
export interface SelectElectiveCourseResult {
  id: string;
  courseId: string;
  status: CourseSelectionStatus;
  selectedAt: string;
}

/** 退选响应 */
export interface DropElectiveCourseResult {
  id: string;
  courseId: string;
  status: CourseSelectionStatus;
  droppedAt: string;
}

/** 标记公告已读响应 */
export interface MarkAnnouncementReadResult {
  announcementId: string;
  read: boolean;
}

// ---------------------------------------------------------------------------
// Mutation 响应数据类型
// ---------------------------------------------------------------------------

/** 提交作业响应 */
export interface SubmitHomeworkResult {
  submissionId: string;
  submittedAt: string;
}

/** 提交考试响应 */
export interface SubmitExamResult {
  submissionId: string;
  submittedAt: string;
  score?: number;
  maxScore?: number;
}

/** 保存考试草稿响应 */
export interface SaveExamDraftResult {
  savedAt: string;
  ok: boolean;
}

/** 标记已读响应 */
export interface MarkAsReadResult {
  notificationId: string;
  read: boolean;
}

/** 批量标记已读响应 */
export interface MarkAllAsReadResult {
  updatedCount: number;
}

/** 记录考试违规响应 */
export interface RecordExamViolationResult {
  recorded: boolean;
  violationCount: number;
}

/** 记录粘贴事件响应 */
export interface RecordPasteEventResult {
  recorded: boolean;
}

/** 更新通知偏好响应 */
export interface UpdateNotificationPreferenceResult {
  type: NotificationType;
  enabled: boolean;
  updatedAt: string;
}

// ---------------------------------------------------------------------------
// 扩展 Mutation 响应数据类型
// ---------------------------------------------------------------------------

/** 更新个人资料响应 */
export interface UpdateProfileResult {
  id: string;
  name: string;
  email: string;
  phone: string;
  gender: string;
  bio: string;
  preferredSubjectId: string;
}

/** 修改密码响应 */
export interface ChangePasswordResult {
  ok: boolean;
}

/** 作业延期申请响应 */
export interface RequestExtensionResult {
  homeworkId: string;
  approved: boolean;
  newDueDate: string;
  reason: string;
}

/** 加入班级响应 */
export interface JoinClassResult {
  classId: string;
  className: string;
  grade: string;
  inviteCode: string;
}

/** 退出班级响应 */
export interface LeaveClassResult {
  classId: string;
  ok: boolean;
}

// ---------------------------------------------------------------------------
// GraphQL 操作名常量（16 查询 + 8 变更）
// ---------------------------------------------------------------------------

/** 查询操作名 */
export type QueryOperationName =
  | "currentUser"
  | "myClasses"
  | "myExams"
  | "examDetail"
  | "myHomework"
  | "homeworkDetail"
  | "myGrades"
  | "myAttendance"
  | "textbooks"
  | "chapters"
  | "learningPath"
  | "studentDashboard"
  | "myWeakness"
  | "myTrend"
  | "myNotifications"
  | "serverTime"
  | "mySchedule"
  | "studentGrowth"
  | "assignmentAnalysis"
  | "myProfile"
  | "myErrorBook"
  | "myLeaveRequests"
  | "myElectiveSelections"
  | "availableElectiveCourses"
  | "myPracticeSessions"
  | "startPracticeSession"
  | "announcements"
  | "announcementDetail"
  | "myLessonPlans"
  | "lessonPlanDetail"
  | "myCoursePlans"
  | "coursePlanDetail"
  | "myReportCard"
  | "myDiagnosticReports"
  | "myMasterySummary";

/** 变更操作名 */
export type MutationOperationName =
  | "submitHomework"
  | "submitExam"
  | "saveExamDraft"
  | "markAsRead"
  | "markAllAsRead"
  | "recordExamViolation"
  | "recordPasteEvent"
  | "updateNotificationPreference"
  | "updateProfile"
  | "changePassword"
  | "requestExtension"
  | "joinClass"
  | "leaveClass"
  | "addErrorBookItem"
  | "updateErrorBookItem"
  | "deleteErrorBookItem"
  | "createLeaveRequest"
  | "cancelLeaveRequest"
  | "selectElectiveCourse"
  | "dropElectiveCourse"
  | "submitPracticeAnswer"
  | "markAnnouncementRead";

/** 全部操作名 */
export type OperationName = QueryOperationName | MutationOperationName;

// ---------------------------------------------------------------------------
// GraphQL 响应映射（operationName → ActionState<数据类型>）
// ---------------------------------------------------------------------------

/** 查询响应映射 */
export interface QueryResponses {
  currentUser: ActionState<CurrentUser>;
  myClasses: ActionState<ClassInfo[]>;
  myExams: ActionState<ExamListItem[]>;
  examDetail: ActionState<ExamDetail>;
  myHomework: ActionState<HomeworkListItem[]>;
  homeworkDetail: ActionState<HomeworkDetail>;
  myGrades: ActionState<GradeRecord[]>;
  myAttendance: ActionState<AttendanceRecord[]>;
  textbooks: ActionState<Textbook[]>;
  chapters: ActionState<ChapterNode[]>;
  learningPath: ActionState<LearningPathNode[]>;
  studentDashboard: ActionState<StudentDashboard>;
  myWeakness: ActionState<WeaknessPoint[]>;
  myTrend: ActionState<TrendDataPoint[]>;
  myNotifications: ActionState<{
    items: NotificationItem[];
    totalCount: number;
    unreadCount: number;
  }>;
  serverTime: ActionState<ServerTime>;
  mySchedule: ActionState<ScheduleItem[]>;
  studentGrowth: ActionState<GrowthDataPoint[]>;
  assignmentAnalysis: ActionState<AssignmentAnalysis>;
  myProfile: ActionState<StudentProfile>;
  myErrorBook: ActionState<ErrorBookData>;
  myLeaveRequests: ActionState<LeaveRequest[]>;
  myElectiveSelections: ActionState<CourseSelection[]>;
  availableElectiveCourses: ActionState<ElectiveCourse[]>;
  myPracticeSessions: ActionState<MyPracticeSessionsData>;
  startPracticeSession: ActionState<PracticeSessionDetail>;
  announcements: ActionState<Announcement[]>;
  announcementDetail: ActionState<Announcement>;
  myLessonPlans: ActionState<LessonPlanListItem[]>;
  lessonPlanDetail: ActionState<LessonPlanDetail>;
  myCoursePlans: ActionState<CoursePlanListItem[]>;
  coursePlanDetail: ActionState<CoursePlanDetail>;
  myReportCard: ActionState<ReportCardData>;
  myDiagnosticReports: ActionState<DiagnosticReport[]>;
  myMasterySummary: ActionState<MasterySummary>;
}

/** 变更响应映射 */
export interface MutationResponses {
  submitHomework: ActionState<SubmitHomeworkResult>;
  submitExam: ActionState<SubmitExamResult>;
  saveExamDraft: ActionState<SaveExamDraftResult>;
  markAsRead: ActionState<MarkAsReadResult>;
  markAllAsRead: ActionState<MarkAllAsReadResult>;
  recordExamViolation: ActionState<RecordExamViolationResult>;
  recordPasteEvent: ActionState<RecordPasteEventResult>;
  updateNotificationPreference: ActionState<UpdateNotificationPreferenceResult>;
  updateProfile: ActionState<UpdateProfileResult>;
  changePassword: ActionState<ChangePasswordResult>;
  requestExtension: ActionState<RequestExtensionResult>;
  joinClass: ActionState<JoinClassResult>;
  leaveClass: ActionState<LeaveClassResult>;
  addErrorBookItem: ActionState<AddErrorBookItemResult>;
  updateErrorBookItem: ActionState<UpdateErrorBookItemResult>;
  deleteErrorBookItem: ActionState<DeleteErrorBookItemResult>;
  createLeaveRequest: ActionState<CreateLeaveRequestResult>;
  cancelLeaveRequest: ActionState<CancelLeaveRequestResult>;
  selectElectiveCourse: ActionState<SelectElectiveCourseResult>;
  dropElectiveCourse: ActionState<DropElectiveCourseResult>;
  submitPracticeAnswer: ActionState<SubmitPracticeAnswerResult>;
  markAnnouncementRead: ActionState<MarkAnnouncementReadResult>;
}

// ---------------------------------------------------------------------------
// 错误码常量（前缀路由 i18n key）
// ---------------------------------------------------------------------------

/** 错误码前缀 */
export const ERROR_CODE_PREFIX = {
  IAM: "IAM_",
  CORE_EDU: "CORE_EDU_",
  BFF_STUDENT: "BFF_STUDENT_",
  GW: "GW_",
  NETWORK: "NETWORK_",
} as const;

/** 常见错误码 */
export const ERROR_CODES = {
  // student-bff 聚合层
  BFF_STUDENT_UPSTREAM_UNAVAILABLE: "BFF_STUDENT_UPSTREAM_UNAVAILABLE",
  BFF_STUDENT_AGGREGATION_FAILED: "BFF_STUDENT_AGGREGATION_FAILED",
  BFF_STUDENT_FORBIDDEN: "BFF_STUDENT_FORBIDDEN",
  BFF_STUDENT_NOT_FOUND: "BFF_STUDENT_NOT_FOUND",
  BFF_STUDENT_VALIDATION_FAILED: "BFF_STUDENT_VALIDATION_FAILED",
  // core-edu 教学核心
  CORE_EDU_EXAM_NOT_FOUND: "CORE_EDU_EXAM_NOT_FOUND",
  CORE_EDU_EXAM_NOT_AVAILABLE: "CORE_EDU_EXAM_NOT_AVAILABLE",
  CORE_EDU_HOMEWORK_NOT_FOUND: "CORE_EDU_HOMEWORK_NOT_FOUND",
  CORE_EDU_HOMEWORK_ALREADY_SUBMITTED: "CORE_EDU_HOMEWORK_ALREADY_SUBMITTED",
  CORE_EDU_EXAM_ALREADY_SUBMITTED: "CORE_EDU_EXAM_ALREADY_SUBMITTED",
  // iam 认证授权
  IAM_UNAUTHORIZED: "IAM_UNAUTHORIZED",
  IAM_FORBIDDEN: "IAM_FORBIDDEN",
  // api-gateway 网关
  GW_RATE_LIMITED: "GW_RATE_LIMITED",
  GW_CIRCUIT_OPEN: "GW_CIRCUIT_OPEN",
  // 前端网络层
  NETWORK_TIMEOUT: "NETWORK_TIMEOUT",
  NETWORK_OFFLINE: "NETWORK_OFFLINE",
} as const;

/** i18n key 前缀映射（按错误码前缀路由） */
export const ERROR_I18N_PREFIX: Record<string, string> = {
  [ERROR_CODE_PREFIX.IAM]: "iam.error",
  [ERROR_CODE_PREFIX.CORE_EDU]: "coreEdu.error",
  [ERROR_CODE_PREFIX.BFF_STUDENT]: "bffStudent.error",
  [ERROR_CODE_PREFIX.GW]: "gateway.error",
  [ERROR_CODE_PREFIX.NETWORK]: "network.error",
};

/**
 * 根据错误码获取 i18n key 前缀
 * @param code 错误码（如 BFF_STUDENT_UPSTREAM_UNAVAILABLE）
 * @returns i18n key 前缀（如 bffStudent.error）
 */
export function getErrorI18nPrefix(code: string): string {
  for (const prefix of Object.keys(ERROR_I18N_PREFIX)) {
    if (code.startsWith(prefix)) {
      return ERROR_I18N_PREFIX[prefix] ?? "common.error";
    }
  }
  return "common.error";
}
