/**
 * admin-portal 视图模型类型定义
 *
 * 对齐 contract.md §2.4 GraphQL Query/Mutation 清单
 * 仲裁：ARB-001 GraphQL admin 命名空间 + ADMIN_ 权限前缀
 */

/** 数据范围（对齐 iam DataScope） */
export type DataScope =
  "ALL" | "SCHOOL" | "GRADE" | "CLASS" | "SUBJECT" | "SELF";

/** 用户状态 */
export type UserStatus = "active" | "disabled" | "locked";

/** 用户视图模型 */
export interface UserViewModel {
  id: string;
  email: string;
  name: string;
  roles: RoleViewModel[];
  status: UserStatus;
  dataScope: DataScope;
  organizationId: string | null;
  schoolName: string | null;
  lastLoginAt: number | null;
  createdAt: number;
  updatedAt: number;
}

/** 角色视图模型 */
export interface RoleViewModel {
  id: string;
  name: string;
  code: string;
  description: string;
  permissions: PermissionViewModel[];
  userCount: number;
  dataScope: DataScope;
  isSystem: boolean;
  createdAt: number;
  updatedAt: number;
}

/** 权限视图模型 */
export interface PermissionViewModel {
  id: string;
  code: string;
  name: string;
  description: string;
  resource: string;
  action: string;
  isSystem: boolean;
}

/** 视口配置视图模型 */
export interface ViewportConfigViewModel {
  id: string;
  key: string;
  label: string;
  route: string;
  icon: string | null;
  sortOrder: number;
  requiredPermission: string | null;
  scope: "teacher" | "student" | "parent" | "admin";
  isVisible: boolean;
}

/** 组织节点视图模型 */
export interface OrganizationNode {
  id: string;
  name: string;
  type: "school" | "grade" | "class";
  parentId: string | null;
  childrenCount: number;
  sortOrder: number;
}

/** 学校设置视图模型 */
export interface SystemSettingsViewModel {
  schoolName: string;
  schoolCode: string;
  academicYear: string;
  semester: "first" | "second";
  contactEmail: string;
  contactPhone: string;
  address: string;
  timezone: string;
  locale: string;
}

/** 班级视图模型（全局管理） */
export interface AdminClassViewModel {
  id: string;
  name: string;
  gradeName: string;
  schoolName: string;
  headTeacherName: string;
  studentCount: number;
  createdAt: number;
}

/** 教师视图模型（全局管理） */
export interface AdminTeacherViewModel {
  id: string;
  email: string;
  name: string;
  schoolName: string;
  subjects: string[];
  classCount: number;
  status: UserStatus;
  lastLoginAt: number | null;
}

/** 学生视图模型（全局管理） */
export interface AdminStudentViewModel {
  id: string;
  email: string;
  name: string;
  className: string;
  gradeName: string;
  schoolName: string;
  guardianName: string | null;
  guardianPhone: string | null;
  status: UserStatus;
}

/** 审计日志视图模型 */
export interface AuditLogViewModel {
  id: string;
  eventId: string;
  occurredAt: number;
  actorUserId: string;
  actorName: string;
  action: string;
  resourceType: string;
  resourceId: string;
  ip: string;
  userAgent: string;
  beforeState: string | null;
  afterState: string | null;
  traceId: string | null;
}

/** 仪表盘统计视图模型 */
export interface AdminDashboardViewModel {
  totalTeachers: number;
  totalStudents: number;
  totalClasses: number;
  totalSchools: number;
  schoolAvgScore: number;
  activeUsersToday: number;
  auditEventsToday: number;
  trend: Array<{
    date: string;
    teachers: number;
    students: number;
    avgScore: number;
  }>;
  serviceHealth: Array<{
    serviceName: string;
    status: "healthy" | "degraded" | "down";
    latencyMs: number;
  }>;
}

/** 列表筛选参数 */
export interface ListFilter {
  page: number;
  pageSize: number;
  search?: string;
  status?: string;
  schoolId?: string;
  gradeId?: string;
  sortField?: string;
  sortOrder?: "asc" | "desc";
}

/** 分页结果 */
export interface PaginatedResult<T> {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
  hasNext: boolean;
}

/** 当前用户信息 */
export interface CurrentUser {
  id: string;
  email: string;
  name: string;
  roles: string[];
  permissions: string[];
  dataScope: DataScope;
  schoolId: string | null;
  schoolName: string | null;
}

/** WebSocket 通知消息 */
export interface WsNotification {
  id: string;
  type: "audit_alert" | "abnormal_login" | "system_error" | "info";
  title: string;
  message: string;
  severity: "info" | "warning" | "error";
  timestamp: number;
}

// ─── 学校组织管理细化 ──────────────────────────────────────────────

/** 学校视图模型 */
export interface SchoolViewModel {
  id: string;
  name: string;
  code: string;
  address: string;
  contactPhone: string;
  contactEmail: string;
  principalName: string | null;
  gradeCount: number;
  classCount: number;
  studentCount: number;
  teacherCount: number;
  createdAt: number;
}

/** 年级视图模型 */
export interface GradeViewModel {
  id: string;
  name: string;
  schoolId: string;
  schoolName: string;
  directorName: string | null;
  classCount: number;
  studentCount: number;
  sortOrder: number;
  createdAt: number;
}

/** 年级概览统计 */
export interface GradeOverviewStats {
  gradeId: string;
  gradeName: string;
  classCount: number;
  studentCount: number;
  teacherCount: number;
  avgScore: number;
  homeworkCount: number;
}

/** 年级洞察视图模型 */
export interface GradeInsightsViewModel {
  gradeId: string;
  gradeName: string;
  schoolWideSummary: {
    totalStudents: number;
    totalClasses: number;
    avgScore: number;
    passingRate: number;
  };
  homeworkTimeline: Array<{
    homeworkId: string;
    title: string;
    className: string;
    avgScore: number;
    submittedCount: number;
    totalCount: number;
    dueDate: string;
  }>;
  classRankings: Array<{
    classId: string;
    className: string;
    avgScore: number;
    rank: number;
    delta: number;
  }>;
}

/** 部门/教研组视图模型 */
export interface DepartmentViewModel {
  id: string;
  name: string;
  schoolId: string;
  schoolName: string;
  leaderName: string | null;
  memberCount: number;
  subject: string | null;
  createdAt: number;
}

/** 学年/学期视图模型 */
export interface AcademicYearViewModel {
  id: string;
  name: string;
  startDate: string;
  endDate: string;
  firstSemesterStart: string;
  firstSemesterEnd: string;
  secondSemesterStart: string;
  secondSemesterEnd: string;
  isCurrent: boolean;
  createdAt: number;
}

// ─── 审计日志子模块 ─────────────────────────────────────────────────

/** 审计总览统计 */
export interface AuditOverviewStats {
  totalEvents: number;
  todayEvents: number;
  uniqueActors: number;
  failedActions: number;
  topActions: Array<{ action: string; count: number }>;
  topResources: Array<{ resource: string; count: number }>;
}

/** 审计趋势数据点 */
export interface AuditTrendPoint {
  date: string;
  count: number;
  action: string;
}

/** 数据变更日志视图模型 */
export interface DataChangeLogViewModel {
  id: string;
  occurredAt: number;
  actorUserId: string;
  actorName: string;
  tableName: string;
  action: "create" | "update" | "delete";
  recordId: string;
  beforeState: string | null;
  afterState: string | null;
  ip: string;
}

/** 登录日志视图模型 */
export interface LoginLogViewModel {
  id: string;
  occurredAt: number;
  userId: string;
  userName: string;
  action: "signin" | "signout" | "signup";
  status: "success" | "failure";
  ip: string;
  userAgent: string;
  failureReason: string | null;
}

// ─── 公告管理 ───────────────────────────────────────────────────────

/** 公告视图模型 */
export interface AnnouncementViewModel {
  id: string;
  title: string;
  content: string;
  status: "draft" | "published" | "archived";
  audience: string[];
  authorName: string;
  isPinned: boolean;
  readCount: number;
  totalCount: number;
  publishedAt: number | null;
  createdAt: number;
  updatedAt: number;
}

// ─── 邀请码管理 ─────────────────────────────────────────────────────

/** 邀请码视图模型 */
export interface InvitationCodeViewModel {
  id: string;
  code: string;
  status: "unused" | "used" | "expired";
  roleId: string | null;
  roleName: string | null;
  classId: string | null;
  className: string | null;
  email: string | null;
  batchId: string;
  usedBy: string | null;
  usedByName: string | null;
  usedAt: number | null;
  createdAt: number;
  expiresAt: number | null;
}

// ─── 文件管理 ───────────────────────────────────────────────────────

/** 文件视图模型 */
export interface FileViewModel {
  id: string;
  filename: string;
  mimeType: string;
  size: number;
  url: string;
  entityType: string;
  entityId: string;
  uploadedByName: string;
  createdAt: number;
}

/** 文件统计 */
export interface FileStats {
  totalFiles: number;
  totalSize: number;
  byMimeType: Array<{ mimeType: string; count: number; size: number }>;
  byEntityType: Array<{ entityType: string; count: number }>;
}

// ─── AI 配置 ─────────────────────────────────────────────────────────

/** AI Provider 视图模型 */
export interface AiProviderViewModel {
  id: string;
  name: string;
  type: string;
  isPublic: boolean;
  isActive: boolean;
  model: string;
  apiBase: string;
  createdBy: string;
  createdAt: number;
}

/** AI 用量视图模型 */
export interface AiUsageViewModel {
  totalRequests: number;
  totalTokens: number;
  totalCost: number;
  byProvider: Array<{
    providerName: string;
    requests: number;
    tokens: number;
    cost: number;
  }>;
  byDay: Array<{
    date: string;
    requests: number;
    tokens: number;
  }>;
}

// ─── 增强系统设置 ───────────────────────────────────────────────────

/** 安全策略配置 */
export interface SecurityPolicy {
  passwordMinLength: number;
  passwordRequireSpecial: boolean;
  passwordRequireUppercase: boolean;
  sessionTimeoutMinutes: number;
  forcePasswordChange: boolean;
}

/** 文件上传配置 */
export interface FileUploadConfig {
  maxFileSize: number;
  allowedTypes: string[];
}

/** 通知配置 */
export interface NotificationConfig {
  notifyNewUser: boolean;
  notifyScheduleChange: boolean;
  notifyAnnouncement: boolean;
}

/** 品牌配置 */
export interface BrandConfig {
  logoUrl: string;
  primaryColor: string;
  schoolMotto: string;
}
