/**
 * MSW Handlers - P7 扩展（备课 + 课程计划 + 诊断 + 错题本 + 自适应练习）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql-p7-insights.ts、workline.md §3 P7 交付物
 *
 * 设计：本文件独立于 handlers.ts，不修改共享文件，最后统一合并。
 * - 拦截 POST /api/v1/teacher/graphql，按 operationName 分发 P7-insights 操作。
 * - 未覆盖的 operation（P2/P3/P4/P5/P7-grades/P7-exams/P7-admin）返回 undefined
 *   → MSW fallthrough 至下游 handler。
 *
 * 注册顺序：p7InsightsHandlers 必须在 handlers 之前注册（见 browser.ts / server.ts）。
 *
 * 覆盖 operationName（对应 graphql-p7-insights.ts）：
 * - LessonPlans / LessonPlanDetail / LessonPlanLibrary
 * - LessonPlanCalendar / LessonPlanHeatmap
 * - CreateLessonPlan / UpdateLessonPlan / AIGenerateLessonPlan / ForkLessonPlan
 * - CoursePlans / CoursePlanDetail / CreateCoursePlan / UpdateCoursePlan
 * - DiagnosticReports / ClassDiagnostic / StudentDiagnostic
 * - ErrorBook
 * - PracticeAnalytics
 */

import { http, HttpResponse } from "msw";
import {
  filterLessonPlans,
  findLessonPlanDetail,
  createMockLessonPlan,
  updateMockLessonPlan,
  generateMockLessonPlan,
  filterLessonPlanLibrary,
  forkMockLessonPlan,
  getLessonPlanCalendar,
  getLessonPlanHeatmap,
} from "./fixtures/lesson-plans";
import {
  filterCoursePlans,
  findCoursePlanDetail,
  createMockCoursePlan,
  updateMockCoursePlan,
} from "./fixtures/course-plans";
import {
  filterDiagnosticReports,
  findClassDiagnostic,
  findStudentDiagnostic,
} from "./fixtures/diagnostic";
import { getErrorBook } from "./fixtures/error-book";
import { getPracticeAnalytics } from "./fixtures/practice";
import type {
  CreateLessonPlanInput,
  UpdateLessonPlanInput,
  AIGenerateLessonPlanInput,
  CreateCoursePlanInput,
  UpdateCoursePlanInput,
  DiagnosticReportType,
  DiagnosticReportStatus,
  CoursePlanStatus,
} from "@/lib/graphql-p7-insights";

/** 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 p7InsightsHandlers = [
  // POST /api/v1/teacher/graphql → P7-insights 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 "LessonPlans": {
        const subject = (variables.subject as string | undefined) ?? null;
        return graphqlData({ lessonPlans: filterLessonPlans(subject) });
      }

      case "LessonPlanDetail": {
        const planId = (variables.planId as string) ?? "";
        const detail = findLessonPlanDetail(planId);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `课案不存在: ${planId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ lessonPlanDetail: detail });
      }

      case "CreateLessonPlan": {
        const input = variables.input as CreateLessonPlanInput;
        return graphqlData({ createLessonPlan: createMockLessonPlan(input) });
      }

      case "UpdateLessonPlan": {
        const input = variables.input as UpdateLessonPlanInput;
        const updated = updateMockLessonPlan(input);
        if (!updated) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `课案不存在: ${input.planId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ updateLessonPlan: updated });
      }

      case "AIGenerateLessonPlan": {
        const input = variables.input as AIGenerateLessonPlanInput;
        return graphqlData({
          aiGenerateLessonPlan: generateMockLessonPlan(input),
        });
      }

      case "LessonPlanLibrary": {
        const subject = (variables.subject as string | undefined) ?? null;
        const grade = (variables.grade as string | undefined) ?? null;
        return graphqlData({
          lessonPlanLibrary: filterLessonPlanLibrary(subject, grade),
        });
      }

      case "ForkLessonPlan": {
        const planId = (variables.planId as string) ?? "";
        const forked = forkMockLessonPlan(planId);
        if (!forked) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `课案库条目不存在: ${planId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ forkLessonPlan: forked });
      }

      case "LessonPlanCalendar": {
        const year = (variables.year as number) ?? 2026;
        const month = (variables.month as number) ?? 7;
        return graphqlData({
          lessonPlanCalendar: getLessonPlanCalendar(year, month),
        });
      }

      case "LessonPlanHeatmap": {
        return graphqlData({
          lessonPlanHeatmap: getLessonPlanHeatmap(),
        });
      }

      // ============ 课程计划 ============
      case "CoursePlans": {
        const status = (variables.status as CoursePlanStatus | undefined) ?? null;
        return graphqlData({ coursePlans: filterCoursePlans(status) });
      }

      case "CoursePlanDetail": {
        const id = (variables.id as string) ?? "";
        const detail = findCoursePlanDetail(id);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `课程计划不存在: ${id}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ coursePlanDetail: detail });
      }

      case "CreateCoursePlan": {
        const input = variables.input as CreateCoursePlanInput;
        return graphqlData({ createCoursePlan: createMockCoursePlan(input) });
      }

      case "UpdateCoursePlan": {
        const input = variables.input as UpdateCoursePlanInput;
        const updated = updateMockCoursePlan(input);
        if (!updated) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `课程计划不存在: ${input.id}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ updateCoursePlan: updated });
      }

      // ============ 诊断 ============
      case "DiagnosticReports": {
        const type = (variables.type as DiagnosticReportType | undefined) ?? null;
        const status = (variables.status as DiagnosticReportStatus | undefined) ?? null;
        return graphqlData({
          diagnosticReports: filterDiagnosticReports(type, status),
        });
      }

      case "ClassDiagnostic": {
        const classId = (variables.classId as string) ?? "";
        const detail = findClassDiagnostic(classId);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `班级诊断不存在: ${classId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ classDiagnostic: detail });
      }

      case "StudentDiagnostic": {
        const studentId = (variables.studentId as string) ?? "";
        const detail = findStudentDiagnostic(studentId);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `学生诊断不存在: ${studentId}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ studentDiagnostic: detail });
      }

      // ============ 错题本 ============
      case "ErrorBook": {
        const subject = (variables.subject as string) ?? "数学";
        const classId = (variables.classId as string | undefined) ?? null;
        return graphqlData({ errorBook: getErrorBook(subject, classId) });
      }

      // ============ 练习 ============
      case "PracticeAnalytics": {
        const classId = (variables.classId as string | undefined) ?? null;
        return graphqlData({
          practiceAnalytics: getPracticeAnalytics(classId),
        });
      }

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