/**
 * MSW Handlers - P7 扩展（行政管理子模块：考勤 + 班级详情 + 课表 + 请假 + 调课）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql-p7-admin.ts、workline.md §3 P7 交付物
 *
 * 设计：本文件独立于 handlers.ts，不修改共享文件，最后统一合并。
 * - 拦截 POST /api/v1/teacher/graphql，按 operationName 分发 P7-admin 操作。
 * - 未覆盖的 operation（P2/P3/P4/P5/P7-grades/P7-exams）返回 undefined → MSW fallthrough 至下游 handler。
 *
 * 注册顺序：p7AdminHandlers 必须在 handlers 之前注册（见 browser.ts / server.ts）。
 *
 * 覆盖 operationName（对应 graphql-p7-admin.ts）：
 * - AttendanceList → 考勤记录列表（按筛选 + 分页）
 * - AttendanceSheet → 考勤录入用学生 + 当天状态
 * - SaveAttendanceSheet → 批量保存考勤
 * - AttendanceStats → 班级考勤统计
 * - AttendanceClassComparison → 班级考勤对比
 * - AttendanceWarnings → 学生考勤预警
 * - AttendanceReport → 周报/月报数据
 * - ClassDetail → 班级详情聚合
 * - ClassSchedule → 班级课表
 * - LeaveRequests → 教师请假审批列表
 * - ApproveLeaveRequest → 批准/拒绝请假
 * - SubmitLeaveRequest → 教师提交请假
 * - ScheduleChanges → 我的调课申请列表
 * - SubmitScheduleChange → 提交调课申请
 */

import { http, HttpResponse } from "msw";
import {
  queryAttendanceList,
  queryAttendanceSheet,
  saveAttendanceSheet,
  queryAttendanceStats,
  queryAttendanceClassComparison,
  queryAttendanceWarnings,
  queryAttendanceReport,
  defaultDateRange,
} from "./fixtures/attendance";
import {
  queryClassDetail,
  queryClassSchedule,
} from "./fixtures/classes-extended";
import {
  queryLeaveRequests,
  approveLeaveRequest,
  submitLeaveRequest,
  queryScheduleChanges,
  submitScheduleChange,
} from "./fixtures/leave-requests";
import { EXTENDED_CLASSES } from "./fixtures/grades-extended";
import type {
  AttendanceListFilter,
  SaveAttendanceSheetInput,
  AttendanceReportType,
  ApproveLeaveRequestInput,
  SubmitLeaveRequestInput,
  SubmitScheduleChangeInput,
  LeaveRequestsFilter,
} from "@/lib/graphql-p7-admin";

/** 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 p7AdminHandlers = [
  // POST /api/v1/teacher/graphql → P7-admin 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 "AttendanceList": {
        const filterRaw = (variables.filter as Partial<AttendanceListFilter> | undefined) ?? {};
        const filter: AttendanceListFilter = {
          classId: filterRaw.classId ?? null,
          startDate: filterRaw.startDate ?? null,
          endDate: filterRaw.endDate ?? null,
          statuses: filterRaw.statuses ?? null,
          page: filterRaw.page ?? 1,
          pageSize: filterRaw.pageSize ?? 30,
        };
        return graphqlData({
          attendanceList: queryAttendanceList(filter),
        });
      }

      case "AttendanceSheet": {
        const classId =
          (variables.classId as string | undefined) ??
          (EXTENDED_CLASSES[0]?.id ?? "");
        const date =
          (variables.date as string | undefined) ??
          defaultDateRange().endDate;
        return graphqlData({
          attendanceSheet: queryAttendanceSheet(classId, date),
        });
      }

      case "SaveAttendanceSheet": {
        const input = variables.input as SaveAttendanceSheetInput;
        return graphqlData({
          saveAttendanceSheet: saveAttendanceSheet(input),
        });
      }

      case "AttendanceStats": {
        const classId =
          (variables.classId as string) ?? (EXTENDED_CLASSES[0]?.id ?? "");
        const { startDate, endDate } = defaultDateRange();
        return graphqlData({
          attendanceStats: queryAttendanceStats(
            classId,
            (variables.startDate as string) ?? startDate,
            (variables.endDate as string) ?? endDate,
          ),
        });
      }

      case "AttendanceClassComparison": {
        const { startDate, endDate } = defaultDateRange();
        return graphqlData({
          attendanceClassComparison: queryAttendanceClassComparison(
            (variables.startDate as string) ?? startDate,
            (variables.endDate as string) ?? endDate,
          ),
        });
      }

      case "AttendanceWarnings": {
        const classId =
          (variables.classId as string) ?? (EXTENDED_CLASSES[0]?.id ?? "");
        const { startDate, endDate } = defaultDateRange();
        return graphqlData({
          attendanceWarnings: queryAttendanceWarnings(
            classId,
            (variables.startDate as string) ?? startDate,
            (variables.endDate as string) ?? endDate,
          ),
        });
      }

      case "AttendanceReport": {
        const classId =
          (variables.classId as string) ?? (EXTENDED_CLASSES[0]?.id ?? "");
        const reportType =
          (variables.reportType as AttendanceReportType | undefined) ??
          "WEEKLY";
        const { startDate, endDate } = defaultDateRange();
        return graphqlData({
          attendanceReport: queryAttendanceReport(
            classId,
            reportType,
            (variables.startDate as string) ?? startDate,
            (variables.endDate as string) ?? endDate,
          ),
        });
      }

      case "ClassDetail": {
        const id =
          (variables.id as string) ?? (EXTENDED_CLASSES[0]?.id ?? "");
        const detail = queryClassDetail(id);
        if (!detail) {
          return HttpResponse.json(
            {
              errors: [
                {
                  message: `班级详情不存在: ${id}`,
                  extensions: { code: "BFF_TEACHER_NOT_FOUND" },
                },
              ],
            },
            { status: 200 },
          );
        }
        return graphqlData({ classDetail: detail });
      }

      case "ClassSchedule": {
        const classId = (variables.classId as string | undefined) ?? undefined;
        return graphqlData({
          classSchedule: queryClassSchedule(classId),
        });
      }

      case "LeaveRequests": {
        const filterRaw = (variables.filter as Partial<LeaveRequestsFilter> | undefined) ?? {};
        const filter: LeaveRequestsFilter = {
          dataScope: filterRaw.dataScope ?? null,
          status: filterRaw.status ?? null,
          page: filterRaw.page ?? 1,
          pageSize: filterRaw.pageSize ?? 50,
        };
        return graphqlData({
          leaveRequests: queryLeaveRequests(filter),
        });
      }

      case "ApproveLeaveRequest": {
        const input = variables.input as ApproveLeaveRequestInput;
        return graphqlData({
          approveLeaveRequest: approveLeaveRequest(input),
        });
      }

      case "SubmitLeaveRequest": {
        const input = variables.input as SubmitLeaveRequestInput;
        return graphqlData({
          submitLeaveRequest: submitLeaveRequest(input),
        });
      }

      case "ScheduleChanges": {
        const page = (variables.page as number | undefined) ?? 1;
        const pageSize = (variables.pageSize as number | undefined) ?? 50;
        return graphqlData({
          scheduleChanges: queryScheduleChanges(page, pageSize),
        });
      }

      case "SubmitScheduleChange": {
        const input = variables.input as SubmitScheduleChangeInput;
        return graphqlData({
          submitScheduleChange: submitScheduleChange(input),
        });
      }

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