/**
 * Mock 考试数据（core-edu 域）
 *
 * 维护者：ai13（teacher-portal）
 */

import type { ExamItem, ExamDetail, ExamQuestion, CreateExamInput } from "@/lib/graphql";

export function generateMockExams(classId: string): ExamItem[] {
  const now = Date.now();
  return [
    {
      id: `${classId}-exam-001`,
      classId,
      title: "2026 春季期中考试",
      description: "覆盖第 1-6 章内容",
      examDate: new Date(now + 7 * 24 * 60 * 60 * 1000).toISOString(),
      duration: 120,
      totalScore: 150,
      status: "PUBLISHED",
    },
    {
      id: `${classId}-exam-002`,
      classId,
      title: "单元测试 - 函数与导数",
      description: null,
      examDate: new Date(now + 14 * 24 * 60 * 60 * 1000).toISOString(),
      duration: 60,
      totalScore: 100,
      status: "DRAFT",
    },
    {
      id: `${classId}-exam-003`,
      classId,
      title: "月考 - 数学综合",
      description: "全册综合测试",
      examDate: new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString(),
      duration: 90,
      totalScore: 120,
      status: "SCORED",
    },
  ];
}

/**
 * 从 examId 反查 classId（mock 数据 ID 规约：${classId}-exam-XXX）
 * 兜底：未匹配时返回 "mock-class"。
 */
function extractClassIdFromExamId(examId: string): string {
  const match = examId.match(/^(.+)-exam-\d+$/);
  return match?.[1] ?? "mock-class";
}

/** 生成 mock 题目列表（固定 4 题） */
function generateMockQuestions(examId: string): ExamQuestion[] {
  const defs: Array<{
    type: ExamQuestion["type"];
    title: string;
    score: number;
  }> = [
    { type: "SINGLE_CHOICE", title: "单项选择：函数的定义域", score: 20 },
    { type: "MULTIPLE_CHOICE", title: "多项选择：导数的几何意义", score: 20 },
    { type: "SHORT_ANSWER", title: "简答：求解方程的实根", score: 30 },
    { type: "ESSAY", title: "论述：函数与不等式的综合应用", score: 50 },
  ];
  return defs.map((d, i) => ({
    id: `${examId}-q-${String(i + 1).padStart(3, "0")}`,
    examId,
    title: d.title,
    type: d.type,
    score: d.score,
    order: i + 1,
  }));
}

/** 按考试 ID 查询详情（含题目列表，MSW mock） */
export function findMockExamDetail(examId: string): ExamDetail {
  const classId = extractClassIdFromExamId(examId);
  const all = generateMockExams(classId);
  const matched = all.find((e) => e.id === examId);
  const base = matched ?? {
    id: examId,
    classId,
    title: "考试详情（mock 兜底）",
    description: "Mock 数据兜底：未匹配到列表中的考试",
    examDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
    duration: 120,
    totalScore: 150,
    status: "DRAFT" as const,
  };
  return {
    ...base,
    questions: generateMockQuestions(examId),
  };
}

/** 创建新考试：基于 input 生成 ExamItem（含随机 ID） */
export function createMockExam(input: CreateExamInput): ExamItem {
  const randomId = Math.random().toString(36).slice(2, 10);
  return {
    id: `${input.classId}-exam-${randomId}`,
    classId: input.classId,
    title: input.title,
    description: input.description ?? null,
    examDate: input.examDate,
    duration: input.duration,
    totalScore: input.totalScore,
    status: "DRAFT",
  };
}
