// parent-portal 类型定义
// 依据：02-architecture-design.md §2 领域模型、§14 通知偏好数据模型、§15 详细组件设计

// ===== 会话状态（Session）=====
export interface UserSession {
  id: string;
  email: string;
  name: string;
  roles: string[];
  permissions: string[];
  dataScope: DataScope;
  schoolId?: string;
}

export type DataScope =
  | "ALL"
  | "SCHOOL"
  | "GRADE"
  | "CLASS"
  | "SUBJECT"
  | "CHILDREN" // 家长特有：仅自己绑定的子女
  | "SELF";

// ===== 视口（Viewport）=====
export interface ViewportItem {
  key: string;
  label: string;
  route: string;
  icon: string | null;
  sortOrder: string;
  requiredPermission: string | null;
  scope: "parent";
}

// ===== 子女信息（ChildInfo）=====
export interface ChildInfo {
  id: string;
  name: string;
  avatar?: string;
  grade: string; // i18n key
  schoolName: string;
  classId: string;
  className?: string;
  isArchived?: boolean; // 已归档（转学/离校）
}

// ===== 子女仪表盘概览（childSummary）=====
export interface ChildSummary {
  childId: string;
  avgScore: number;
  classRank: number;
  classSize: number;
  attendanceRate: number; // 0-1
  pendingHomeworkCount: number;
  recentGradeTrend: "up" | "down" | "stable";
  recentScores: GradeDataPoint[];
  upcomingEvents?: UpcomingEvent[];
}

export interface UpcomingEvent {
  id: string;
  type: "exam" | "homework" | "activity";
  title: string;
  dueDate: string; // ISO 8601
}

// ===== 成绩（Grade）=====
export interface GradeDataPoint {
  examId: string;
  examName: string;
  examDate: string; // ISO 8601
  subject: string;
  studentScore: number;
  classAverage?: number;
  classMax?: number;
  classMin?: number;
  gradeLevel: "A" | "B" | "C" | "D" | "F";
}

// ===== 考勤（Attendance）=====
export interface AttendanceRecord {
  id: string;
  date: string; // ISO 8601 date
  status: "present" | "absent" | "late" | "leave";
  note?: string;
}

// ===== 作业（Homework）=====
export interface HomeworkItem {
  id: string;
  title: string;
  subject: string;
  className: string;
  assignedDate: string; // ISO 8601
  dueDate: string; // ISO 8601
  status: "not_started" | "in_progress" | "submitted" | "graded";
  score?: number;
  maxScore: number;
  feedback?: string;
}

// ===== 学情分析 =====
export interface WeaknessPoint {
  id: string;
  knowledgePoint: string;
  masteryLevel: number; // 0-1
  subject: string;
  recommendation?: string;
}

export interface LearningTrend {
  childId: string;
  period: "week" | "month" | "semester";
  dataPoints: TrendDataPoint[];
}

export interface TrendDataPoint {
  date: string;
  score: number;
  subject?: string;
}

// ===== 通知 =====
export interface NotificationItem {
  id: string;
  childId: string | null;
  eventType: NotificationEventType;
  title: string; // i18n key
  body: string; // i18n key + 参数
  read: boolean;
  createdAt: string; // ISO 8601
  actionUrl?: string;
  pinned?: boolean;
}

// ===== 通知偏好（02 §14 通知偏好数据模型）=====
export type NotificationEventType =
  | "grade_recorded"
  | "homework_graded"
  | "homework_assigned"
  | "exam_published"
  | "attendance_alert"
  | "school_announcement"
  | "teacher_message"
  | "fee_reminder"
  | "event_invitation";

export type NotificationChannel =
  "in_app" | "push" | "sms" | "email" | "wechat";

export interface NotificationPreferences {
  parentId: string;
  // 三维矩阵：children[eventType][channel] = enabled
  // Partial 内层：允许部分 eventType 未设置（新增子女时不必预填全部事件）
  preferences: Record<
    string, // childId（"*" 表示全部子女）
    Partial<
      Record<
        NotificationEventType,
        Partial<Record<NotificationChannel, boolean>>
      >
    >
  >;
  // 全局默认
  defaults: Record<
    NotificationEventType,
    Partial<Record<NotificationChannel, boolean>>
  >;
  updatedAt: string; // ISO 8601
}

export interface AvailableChannels {
  in_app: boolean;
  push: boolean;
  sms: boolean;
  email: boolean;
  wechat: boolean;
}

// ===== API 错误 =====
export interface ApiError {
  code: string;
  message: string;
  details?: unknown;
  traceId?: string;
}

// ===== ActionState（统一响应契约）=====
export type ActionState<T> =
  { success: true; data: T } | { success: false; error: ApiError };

// ===== 登录响应 =====
export interface LoginResponse {
  user: UserSession;
  tokens: {
    accessToken: string;
    refreshToken: string;
    expiresIn: number;
  };
}

// ===== WebSocket 推送事件（P5）=====
export type WebSocketEvent =
  | {
      type: "NotificationRequested";
      notification: NotificationItem;
    }
  | {
      type: "GradeRecorded";
      childId: string;
      examId: string;
      examName: string;
      score: number;
    }
  | {
      type: "SchoolAnnouncement";
      title: string;
      body: string;
    }
  | {
      type: "ChildUnbound";
      childId: string;
    }
  | {
      type: "ChildBound";
      child: ChildInfo;
    };

// ===== 跨标签同步消息 =====
export type SyncMessage =
  | {
      type: "child-switched";
      childId: string;
      ts: number;
      source: string;
    }
  | {
      type: "child-unbound";
      childId: string;
      ts: number;
      source: string;
    }
  | {
      type: "preferences-updated";
      ts: number;
      source: string;
    };
