/**
 * MSW Handlers - P7 扩展（选修课 + 富文本编辑 + 监考 + 扫描批改 + 课标热力图）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql-p7-advanced.ts、workline.md §3 P7 交付物
 *
 * 设计：本文件独立于 handlers.ts，不修改共享文件，最后统一合并。
 * - 拦截 POST /api/v1/teacher/graphql，按 operationName 分发 P7-advanced 操作。
 * - 未覆盖的 operation（P2/P3/P4/P5/P7-grades/exams/admin/insights）返回 undefined → MSW fallthrough 至下游 handler。
 *
 * 注册顺序：p7AdvancedHandlers 必须在 handlers 之前注册（见 browser.ts / server.ts）。
 *
 * 覆盖 operationName（对应 graphql-p7-advanced.ts）：
 * - ElectiveCourses / ElectiveCourseDetail → 选修课列表 + 详情
 * - CreateElectiveCourse / UpdateElectiveCourse / PublishElectiveCourse / CancelElectiveCourse
 * - ExamRichEditor / SaveExamRichContent → 富文本试卷内容
 * - ProctoringStatus / ProctoringEvent → 监考状态 + 事件
 * - SubmissionScanGrading / SaveScanGrading → 扫描批改
 * - LessonPlanHeatmap → 课标覆盖热力图
 */

import { http, HttpResponse } from "msw";
import {
  generateElectiveCourses,
  findElectiveCourseDetail,
  createMockElectiveCourse,
  updateMockElectiveCourse,
  publishMockElectiveCourse,
  cancelMockElectiveCourse,
} from "./fixtures/elective";
import {
  findProctoringStatus,
  createProctoringEvent,
} from "./fixtures/proctoring";
import {
  findScanGrading,
  saveScanGrading,
} from "./fixtures/scan-grading";
import {
  findLessonPlanHeatmap,
} from "./fixtures/lesson-plan-heatmap";
import type {
  CreateElectiveCourseInput,
  UpdateElectiveCourseInput,
  ProctoringEventInput,
  SaveScanGradingInput,
  SaveExamRichContentInput,
} from "@/lib/graphql-p7-advanced";

/** GraphQL 响应体（urql 期望 { data: ... }） */
function graphqlData<T>(data: T) {
  return HttpResponse.json({ data });
}

function extractOperationName(query?: string): string {
  if (!query) return "Unknown";
  const match = query.match(/(?:query|mutation)\s+(\w+)/);
  return match?.[1] ?? "Unknown";
}

export const p7AdvancedHandlers = [
  // POST /api/v1/teacher/graphql → P7-advanced operations（未覆盖的 fallthrough 至 handlers.ts）
  http.post("*/api/v1/teacher/graphql", async ({ request }) => {
    const body = (await request.json()) as {
      operationName?: string;
      query?: string;
      variables?: Record<string, unknown>;
    };

    const operationName =
      body.operationName ?? extractOperationName(body.query);
    const variables = body.variables ?? {};

    switch (operationName) {
      // ===== 选修课 =====
      case "ElectiveCourses": {
        const status = variables.status as string | undefined;
        const subject = variables.subject as string | undefined;
        return graphqlData({
          electiveCourses: generateElectiveCourses(status, subject),
        });
      }

      case "ElectiveCourseDetail": {
        const id = (variables.id as string) ?? "";
        const detail = findElectiveCourseDetail(id);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `选修课不存在: ${id}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ electiveCourseDetail: detail });
      }

      case "CreateElectiveCourse": {
        const input = variables.input as CreateElectiveCourseInput;
        return graphqlData({
          createElectiveCourse: createMockElectiveCourse(input),
        });
      }

      case "UpdateElectiveCourse": {
        const input = variables.input as UpdateElectiveCourseInput;
        return graphqlData({
          updateElectiveCourse: updateMockElectiveCourse(input),
        });
      }

      case "PublishElectiveCourse": {
        const id = (variables.id as string) ?? "";
        return graphqlData({
          publishElectiveCourse: publishMockElectiveCourse(id),
        });
      }

      case "CancelElectiveCourse": {
        const id = (variables.id as string) ?? "";
        return graphqlData({
          cancelElectiveCourse: cancelMockElectiveCourse(id),
        });
      }

      // ===== 富文本编辑 =====
      case "ExamRichEditor": {
        const examId = (variables.examId as string) ?? "";
        // mock：返回默认富文本结构
        const now = new Date().toISOString();
        return graphqlData({
          examRichEditor: {
            examId,
            title: "富文本试卷（mock）",
            totalScore: 100,
            questionCount: 4,
            content: {
              type: "doc",
              content: [
                {
                  type: "heading",
                  attrs: { level: 1 },
                  content: [{ type: "text", text: "2026 春季期中考试" }],
                },
                {
                  type: "paragraph",
                  content: [
                    { type: "text", text: "请考生认真作答，满分 100 分。" },
                  ],
                },
              ],
            },
            updatedAt: now,
          },
        });
      }

      case "SaveExamRichContent": {
        const input = variables.input as SaveExamRichContentInput;
        const now = new Date().toISOString();
        return graphqlData({
          saveExamRichContent: {
            examId: input.examId,
            updatedAt: now,
          },
        });
      }

      // ===== 监考 =====
      case "ProctoringStatus": {
        const examId = (variables.examId as string) ?? "";
        return graphqlData({
          proctoringStatus: findProctoringStatus(examId),
        });
      }

      case "ProctoringEvent": {
        const input = variables.input as ProctoringEventInput;
        return graphqlData({
          proctoringEvent: createProctoringEvent(input),
        });
      }

      // ===== 扫描批改 =====
      case "SubmissionScanGrading": {
        const submissionId = (variables.submissionId as string) ?? "";
        const detail = findScanGrading(submissionId);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `扫描批改视图不存在: ${submissionId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ submissionScanGrading: detail });
      }

      case "SaveScanGrading": {
        const input = variables.input as SaveScanGradingInput;
        return graphqlData({
          saveScanGrading: saveScanGrading(input),
        });
      }

      // ===== 课标热力图 =====
      case "LessonPlanHeatmap": {
        const textbookId = (variables.textbookId as string) ?? "";
        const heatmap = findLessonPlanHeatmap(textbookId);
        if (!heatmap) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `教材热力图不存在: ${textbookId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ lessonPlanHeatmap: heatmap });
      }

      default:
        // 未覆盖的 P2/P3/P4/P5/P7-grades/exams/admin/insights operation：返回 undefined → fallthrough
        return undefined;
    }
  }),
];
