/**
 * MSW Handlers - P7 扩展（成绩完整子模块 + 作业批改链路）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql-p7-grades.ts、workline.md §3 P7 交付物
 *
 * 设计：本文件独立于 handlers.ts，不修改共享文件，最后统一合并。
 * - 拦截 POST /api/v1/teacher/graphql，按 operationName 分发 P7 操作。
 * - 未覆盖的 operation（P2/P3/P4/P5）返回 undefined → MSW fallthrough 至下游 handler。
 *
 * 注册顺序：p7Handlers 必须在 handlers 之前注册（见 browser.ts / server.ts）。
 *
 * 覆盖 operationName（对应 graphql-p7-grades.ts）：
 * - GradeEntry → 成绩录入列表（按 examId + classId）
 * - SaveGradeEntries → 批量保存成绩录入
 * - GradeStats → 班级成绩统计
 * - GradeAnalytics → 成绩分析
 * - ReportCard → 学生成绩报告卡
 * - HomeworkSubmissions → 作业提交统计列表
 * - HomeworkAssignmentSubmissions → 按作业 ID 拉取所有提交
 * - GradeSubmission → 单份提交批改
 */

import { http, HttpResponse } from "msw";
import {
  generateGradeEntries,
  saveGradeEntries,
  generateGradeStats,
  generateGradeAnalytics,
  generateReportCard,
  EXTENDED_CLASSES,
} from "./fixtures/grades-extended";
import {
  generateHomeworkSubmissionStats,
  generateAssignmentSubmissions,
  gradeSubmission,
  generateAiBatchGrading,
} from "./fixtures/homework-submissions";
import type { GradeSubmissionInput, SaveGradeEntriesInput } from "@/lib/graphql-p7-grades";

/** 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 p7Handlers = [
  // POST /api/v1/teacher/graphql → P7 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 "GradeEntry": {
        const examId = variables.examId as string;
        const classId = variables.classId as string;
        // classId 兜底为第一个班级
        const targetClassId =
          classId || (EXTENDED_CLASSES[0]?.id ?? "");
        return graphqlData({
          gradeEntry: generateGradeEntries(examId, targetClassId),
        });
      }

      case "SaveGradeEntries": {
        const input = variables.input as SaveGradeEntriesInput;
        return graphqlData({
          saveGradeEntries: saveGradeEntries(input),
        });
      }

      case "GradeStats": {
        const classId =
          (variables.classId as string) ||
          (EXTENDED_CLASSES[0]?.id ?? "");
        const subject = (variables.subject as string) ?? "数学";
        return graphqlData({
          gradeStats: generateGradeStats(classId, subject),
        });
      }

      case "GradeAnalytics": {
        const classId =
          (variables.classId as string) ||
          (EXTENDED_CLASSES[0]?.id ?? "");
        return graphqlData({
          gradeAnalytics: generateGradeAnalytics(classId),
        });
      }

      case "ReportCard": {
        const studentId = variables.studentId as string;
        const academicYear = variables.academicYear as string | undefined;
        const semester = variables.semester as string | undefined;
        const card = generateReportCard(studentId, academicYear, semester);
        if (!card) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `报告卡不存在: ${studentId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ reportCard: card });
      }

      case "HomeworkSubmissions": {
        const classId = variables.classId as string | undefined;
        const status = variables.status as string | undefined;
        return graphqlData({
          homeworkSubmissions: generateHomeworkSubmissionStats(
            classId,
            status,
          ),
        });
      }

      case "HomeworkAssignmentSubmissions": {
        const homeworkId = variables.homeworkId as string;
        return graphqlData({
          homeworkAssignmentSubmissions:
            generateAssignmentSubmissions(homeworkId),
        });
      }

      case "GradeSubmission": {
        const input = variables.input as GradeSubmissionInput;
        return graphqlData({
          gradeSubmission: gradeSubmission(input),
        });
      }

      // 批量 AI 评分建议（自定义 operation，非 graphql-p7-grades.ts 定义）
      case "AiBatchGrading": {
        const homeworkId = variables.homeworkId as string;
        return graphqlData({
          aiBatchGrading: generateAiBatchGrading(homeworkId),
        });
      }

      default:
        // 未覆盖的 P2/P3/P4/P5 operation：返回 undefined → fallthrough 至 handlers.ts
        return undefined;
    }
  }),
];
