/**
 * Mock 选修课数据（P7-advanced：选修课模块）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 10 个选修课（覆盖 draft/open/closed/cancelled 状态）
 * - 每个含学生选课列表
 * - 按 ID 查找详情 + CRUD mock 函数
 */

import type {
  ElectiveCourseItem,
  ElectiveCourseDetail,
  ElectiveStudent,
  ElectiveCourseStatus,
  CreateElectiveCourseInput,
  UpdateElectiveCourseInput,
} from "@/lib/graphql-p7-advanced";

/** 当前教师 ID（mock：登录用户） */
export const CURRENT_TEACHER_ID = "tch-001";
export const CURRENT_TEACHER_NAME = "王老师";

/** 10 个选修课定义（覆盖 4 种状态） */
const ELECTIVE_COURSE_DEFS: Array<{
  id: string;
  title: string;
  subject: string;
  grade: string;
  capacity: number;
  teacherId: string;
  teacherName: string;
  semester: string;
  status: ElectiveCourseStatus;
  description: string | null;
  enrolledCount: number;
}> = [
  {
    id: "ele-001",
    title: "趣味数学建模",
    subject: "数学",
    grade: "高一",
    capacity: 40,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "open",
    description: "通过实际案例学习数学建模方法",
    enrolledCount: 32,
  },
  {
    id: "ele-002",
    title: "现代文学赏析",
    subject: "语文",
    grade: "高二",
    capacity: 35,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "open",
    description: "阅读分析当代经典文学作品",
    enrolledCount: 28,
  },
  {
    id: "ele-003",
    title: "物理实验探究",
    subject: "物理",
    grade: "高一",
    capacity: 30,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "closed",
    description: "动手实验，探究物理规律",
    enrolledCount: 30,
  },
  {
    id: "ele-004",
    title: "英语口语训练",
    subject: "英语",
    grade: "高二",
    capacity: 25,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "open",
    description: null,
    enrolledCount: 20,
  },
  {
    id: "ele-005",
    title: "化学与生活",
    subject: "化学",
    grade: "高一",
    capacity: 40,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "draft",
    description: "了解化学在日常生活中的应用",
    enrolledCount: 0,
  },
  {
    id: "ele-006",
    title: "生物多样性",
    subject: "生物",
    grade: "高二",
    capacity: 35,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "draft",
    description: "探索生态系统与物种保护",
    enrolledCount: 0,
  },
  {
    id: "ele-007",
    title: "历史人物评说",
    subject: "历史",
    grade: "高二",
    capacity: 50,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2025秋季",
    status: "closed",
    description: "评析历史人物的功过是非",
    enrolledCount: 48,
  },
  {
    id: "ele-008",
    title: "地理与环境",
    subject: "地理",
    grade: "高一",
    capacity: 40,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2025秋季",
    status: "cancelled",
    description: "已取消：教师调动",
    enrolledCount: 0,
  },
  {
    id: "ele-009",
    title: "信息技术基础",
    subject: "信息技术",
    grade: "高一",
    capacity: 60,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "open",
    description: "学习编程基础与算法思维",
    enrolledCount: 55,
  },
  {
    id: "ele-010",
    title: "美术鉴赏",
    subject: "美术",
    grade: "高二",
    capacity: 30,
    teacherId: CURRENT_TEACHER_ID,
    teacherName: CURRENT_TEACHER_NAME,
    semester: "2026春季",
    status: "closed",
    description: "鉴赏中外美术名作",
    enrolledCount: 30,
  },
];

/** 确定性伪随机 */
function seededRandom(seed: number): number {
  const x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
}

function strToSeed(s: string): number {
  let h = 0;
  for (let i = 0; i < s.length; i++) {
    h = (h * 31 + s.charCodeAt(i)) | 0;
  }
  return Math.abs(h) + 1;
}

/** 生成单个选修课的学生列表（按 enrolledCount） */
function generateStudents(
  courseId: string,
  enrolledCount: number,
): ElectiveStudent[] {
  const list: ElectiveStudent[] = [];
  const now = Date.now();
  for (let i = 1; i <= enrolledCount; i++) {
    const seed = strToSeed(`${courseId}-stu-${i}`);
    const isCancelled = seededRandom(seed) > 0.9;
    list.push({
      studentId: `stu-${courseId}-${String(i).padStart(3, "0")}`,
      studentName: `学生${String(i).padStart(2, "0")}`,
      studentNo: `2026${String(i).padStart(4, "0")}`,
      enrolledAt: new Date(now - i * 24 * 60 * 60 * 1000).toISOString(),
      status: isCancelled ? "cancelled" : "enrolled",
    });
  }
  return list;
}

/** 生成选修课列表（可按 status / subject 过滤） */
export function generateElectiveCourses(
  status?: string,
  subject?: string,
): ElectiveCourseItem[] {
  return ELECTIVE_COURSE_DEFS.filter((c) => {
    if (status && c.status !== status) return false;
    if (subject && c.subject !== subject) return false;
    return true;
  }).map((c) => ({
    id: c.id,
    title: c.title,
    subject: c.subject,
    grade: c.grade,
    capacity: c.capacity,
    enrolledCount: c.enrolledCount,
    teacherId: c.teacherId,
    teacherName: c.teacherName,
    semester: c.semester,
    status: c.status,
    description: c.description,
  }));
}

/** 按 ID 查找选修课详情（含学生列表） */
export function findElectiveCourseDetail(
  id: string,
): ElectiveCourseDetail | null {
  const def = ELECTIVE_COURSE_DEFS.find((c) => c.id === id);
  if (!def) return null;
  const now = Date.now();
  return {
    id: def.id,
    title: def.title,
    subject: def.subject,
    grade: def.grade,
    capacity: def.capacity,
    enrolledCount: def.enrolledCount,
    teacherId: def.teacherId,
    teacherName: def.teacherName,
    semester: def.semester,
    status: def.status,
    description: def.description,
    students: generateStudents(def.id, def.enrolledCount),
    createdAt: new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date(now - 1 * 24 * 60 * 60 * 1000).toISOString(),
  };
}

/** 创建选修课（mock：返回新 ID + draft 状态） */
export function createMockElectiveCourse(
  _input: CreateElectiveCourseInput,
): { id: string; status: ElectiveCourseStatus; updatedAt: string } {
  const randomId = `ele-${Math.random().toString(36).slice(2, 8)}`;
  return {
    id: randomId,
    status: "draft",
    updatedAt: new Date().toISOString(),
  };
}

/** 更新选修课（mock：返回更新时间） */
export function updateMockElectiveCourse(
  input: UpdateElectiveCourseInput,
): { id: string; status: ElectiveCourseStatus; updatedAt: string } {
  return {
    id: input.id,
    status: "draft",
    updatedAt: new Date().toISOString(),
  };
}

/** 发布选修课（mock：返回 open 状态） */
export function publishMockElectiveCourse(
  id: string,
): { id: string; status: ElectiveCourseStatus; updatedAt: string } {
  return {
    id,
    status: "open",
    updatedAt: new Date().toISOString(),
  };
}

/** 取消选修课（mock：返回 cancelled 状态） */
export function cancelMockElectiveCourse(
  id: string,
): { id: string; status: ElectiveCourseStatus; updatedAt: string } {
  return {
    id,
    status: "cancelled",
    updatedAt: new Date().toISOString(),
  };
}
