// MSW handlers：parent-bff GraphQL + iam REST mock
// 依据：
// - 02-architecture-design.md §8 MSW 模拟未就绪上游
// - F9 GraphQL（查询走 GraphQL）
// - ISSUE-004 登录走 REST
// - ISSUE-010 iam GetChildrenByParent P0 阻塞 → myChildren 返回 mock
// - ISSUE-033 通知偏好 P4 localStorage 降级 → updateNotificationPreferences 仍 mock 200

import { http, HttpResponse, graphql } from "msw";
import type { ActionState, LoginResponse } from "@/types";
import {
  mockParent,
  mockChildren,
  mockChildSummary,
  mockGradeDataPoints,
  mockAttendance,
  mockHomework,
  mockWeakness,
  mockLearningTrend,
  mockNotifications,
  mockNotificationPreferences,
  mockLoginResponse,
} from "./fixtures";

// ===== REST handlers（iam login/refresh，ISSUE-004）=====
const restHandlers = [
  http.post("/api/v1/iam/login", async ({ request }) => {
    const body = (await request.json()) as { email: string; password: string };
    // mock：任意 parent@example.com / password 通过
    if (body.email === "parent@example.com" && body.password === "password") {
      const res: ActionState<LoginResponse> = {
        success: true,
        data: mockLoginResponse,
      };
      return HttpResponse.json(res);
    }
    const err: ActionState<never> = {
      success: false,
      error: {
        code: "IAM_INVALID_CREDENTIALS",
        message: "邮箱或密码错误",
      },
    };
    return HttpResponse.json(err, { status: 401 });
  }),

  http.post("/api/v1/iam/refresh", async ({ request }) => {
    const body = (await request.json()) as { refreshToken: string };
    if (body.refreshToken === "mock-refresh-token-parent-001") {
      const res: ActionState<{ tokens: LoginResponse["tokens"] }> = {
        success: true,
        data: {
          tokens: {
            accessToken: "mock-access-token-parent-001-renewed",
            refreshToken: "mock-refresh-token-parent-001-renewed",
            expiresIn: 3600,
          },
        },
      };
      return HttpResponse.json(res);
    }
    return HttpResponse.json(
      {
        success: false,
        error: { code: "IAM_INVALID_REFRESH", message: "refresh token 无效" },
      },
      { status: 401 },
    );
  }),
];

// ===== GraphQL handlers（parent-bff，F9）=====
const graphqlHandlers = [
  graphql.query("CurrentUser", () => {
    return HttpResponse.json({
      data: {
        currentUser: mockParent,
      },
    });
  }),

  graphql.query("MyChildren", () => {
    return HttpResponse.json({
      data: {
        myChildren: mockChildren,
      },
    });
  }),

  graphql.query("ChildSummary", ({ variables }) => {
    const childId = variables.childId as string;
    return HttpResponse.json({
      data: {
        childSummary: { ...mockChildSummary, childId },
      },
    });
  }),

  graphql.query("ChildGrades", () => {
    return HttpResponse.json({
      data: {
        childGrades: mockGradeDataPoints,
      },
    });
  }),

  graphql.query("ChildAttendance", () => {
    return HttpResponse.json({
      data: {
        childAttendance: mockAttendance,
      },
    });
  }),

  graphql.query("ChildHomework", () => {
    return HttpResponse.json({
      data: {
        childHomework: mockHomework,
      },
    });
  }),

  graphql.query("ChildWeakness", () => {
    return HttpResponse.json({
      data: {
        childWeakness: mockWeakness,
      },
    });
  }),

  graphql.query("ChildTrend", ({ variables }) => {
    return HttpResponse.json({
      data: {
        childTrend: {
          ...mockLearningTrend,
          childId: variables.childId as string,
        },
      },
    });
  }),

  graphql.query("MyNotifications", () => {
    return HttpResponse.json({
      data: {
        myNotifications: mockNotifications,
      },
    });
  }),

  graphql.query("MyNotificationPreferences", () => {
    return HttpResponse.json({
      data: {
        myNotificationPreferences: mockNotificationPreferences,
      },
    });
  }),

  graphql.mutation("MarkAsRead", ({ variables }) => {
    const notificationId = variables.notificationId as string;
    return HttpResponse.json({
      data: {
        markAsRead: { id: notificationId, read: true },
      },
    });
  }),

  graphql.mutation("MarkAllAsRead", () => {
    return HttpResponse.json({
      data: {
        markAllAsRead: { count: mockNotifications.length },
      },
    });
  }),

  // ISSUE-033：P4 localStorage 降级，但仍 mock 返回 200（前端优先用 localStorage）
  graphql.mutation("UpdateNotificationPreferences", ({ variables }) => {
    return HttpResponse.json({
      data: {
        updateNotificationPreferences: {
          parentId: (variables as { parentId: string }).parentId,
          updatedAt: new Date().toISOString(),
        },
      },
    });
  }),
];

export const handlers = [...restHandlers, ...graphqlHandlers];
