/**
 * MSW Handlers - P5 扩展（通知中心 + AI 辅助）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：02-architecture-design.md §5 实时推送、§6 AI 辅助
 *
 * 设计：本文件独立于 handlers.ts，不修改共享文件，最后统一合并。
 * - 拦截 POST /api/v1/teacher/graphql，按 operationName 分发 P5 操作。
 * - 未覆盖的 operation（P2/P3）返回 undefined → MSW fallthrough 至 handlers.ts。
 *   （MSW v2：resolver 返回 undefined 时继续匹配下一个 handler，见 executeHandlers.js）
 *
 * 注册顺序：p5Handlers 必须在 handlers 之前注册（见 browser.ts / server.ts）。
 */

import { http, HttpResponse } from "msw";
import { mockNotifications, findNotification } from "./fixtures/notifications";
import {
  mockGeneratedQuestion,
  mockLessonPlan,
  mockReport,
} from "./fixtures/ai";

/** 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 p5Handlers = [
  // POST /api/v1/teacher/graphql → P5 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 "MyNotifications": {
        const unreadOnly = variables.unreadOnly as boolean | undefined;
        const list = unreadOnly
          ? mockNotifications.filter((n) => !n.read)
          : mockNotifications;
        return graphqlData({ myNotifications: list });
      }

      case "MarkAsRead": {
        const id = variables.id as string;
        const found = findNotification(id);
        if (!found) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `通知不存在: ${id}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({
          markAsRead: { id, read: true },
        });
      }

      case "GenerateQuestion": {
        const input = variables.input as {
          subject?: string;
          questionType?: string;
          difficulty?: string;
          knowledgePoints?: string;
          count?: number;
        };
        const seq = String(Date.now()).slice(-6);
        return graphqlData({
          generateQuestion: {
            ...mockGeneratedQuestion,
            id: `ai-q-${seq}`,
            question: `【${input.subject ?? "数学"}·${input.difficulty ?? "中等"}】${mockGeneratedQuestion.question}`,
            explanation: `知识点：${input.knowledgePoints ?? "导数应用"}\n${mockGeneratedQuestion.explanation}`,
          },
        });
      }

      case "GenerateLessonPlan": {
        const input = variables.input as {
          classId?: string;
          subject?: string;
          topic?: string;
        };
        const seq = String(Date.now()).slice(-6);
        return graphqlData({
          generateLessonPlan: {
            ...mockLessonPlan,
            id: `ai-lp-${seq}`,
            content: `# 教案：${input.topic ?? "函数的单调性与极值"}\n\n班级：${input.classId ?? "-"}  科目：${input.subject ?? "数学"}\n${mockLessonPlan.content}`,
          },
        });
      }

      case "GenerateReport": {
        const input = variables.input as {
          classId?: string;
          reportType?: string;
          studentId?: string;
        };
        const seq = String(Date.now()).slice(-6);
        const scope =
          input.reportType === "单生报告" && input.studentId
            ? `学生 ${input.studentId}`
            : `班级 ${input.classId ?? "-"}`;
        return graphqlData({
          generateReport: {
            ...mockReport,
            id: `ai-rpt-${seq}`,
            content: `# 学情报告（${input.reportType ?? "班级周报"}）- ${scope}\n${mockReport.content}`,
          },
        });
      }

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