/**
 * Auth Resolver - currentUser Query.
 *
 * 仲裁依据:
 *   - student-bff.schema.graphql Query.currentUser
 *   - coord-final-decisions §2 B2 (gRPC 调用 iam)
 *   - coord-final-decisions §2 B3 (BFF 豁免 @RequirePermission, 仅校验 x-user-id)
 *
 * 聚合: iam.GetUserInfo + iam.GetEffectivePermissions + iam.GetViewports
 *   并行调用 (Promise.allSettled), 部分失败走降级模式方案 B.
 */
import type { StudentBffContext } from "../../shared/graphql/yoga.js";
import type { DownstreamResponse } from "@edu/shared-ts/bff";
import { UnauthorizedError } from "../../shared/errors/application-error.js";

export const authResolvers = {
  Query: {
    /**
     * currentUser: 获取当前学生信息 + 权限 + 视口.
     * @permission STUDENT_DASHBOARD_READ
     * @dataScope OWN
     */
    async currentUser(
      _parent: unknown,
      _args: unknown,
      ctx: StudentBffContext,
    ): Promise<unknown> {
      if (!ctx.userId) {
        throw new UnauthorizedError();
      }

      const results = await ctx.downstream.callAll([
        {
          service: "iam",
          method: "GetUserInfo",
          request: { userId: ctx.userId },
          options: {
            traceId: ctx.traceId,
            metadata: { "x-user-id": ctx.userId },
          },
        },
        {
          service: "iam",
          method: "GetEffectivePermissions",
          request: { userId: ctx.userId },
          options: {
            traceId: ctx.traceId,
            metadata: { "x-user-id": ctx.userId },
          },
        },
        {
          service: "iam",
          method: "GetViewports",
          request: { userId: ctx.userId },
          options: {
            traceId: ctx.traceId,
            metadata: { "x-user-id": ctx.userId },
          },
        },
      ] as const);

      const [userInfoResp, permsResp, viewportsResp] = results as [
        DownstreamResponse<unknown>,
        DownstreamResponse<unknown>,
        DownstreamResponse<unknown>,
      ];

      const degradedFields: string[] = [];
      if (!userInfoResp.success) degradedFields.push("user");
      if (!permsResp.success) degradedFields.push("effectivePermissions");
      if (!viewportsResp.success) degradedFields.push("viewports");

      // 必需字段失败时抛错
      if (!userInfoResp.success) {
        throw new Error(
          `Failed to fetch user info: ${userInfoResp.error.message}`,
        );
      }

      const userInfo = userInfoResp.data as {
        userId: string;
        email: string;
        name: string;
        avatar: string | null;
        roles: string[];
      };
      const permissions = permsResp.success
        ? (permsResp.data as { permissions: string[] }).permissions
        : [];
      const viewports = viewportsResp.success
        ? (viewportsResp.data as { navigation: unknown[]; dataScope: unknown })
        : { navigation: [], dataScope: {} };

      // 返回扁平对象，对齐 CurrentUserPayload schema
      return {
        user: {
          id: userInfo.userId,
          email: userInfo.email,
          name: userInfo.name,
          avatar: userInfo.avatar,
          roles: userInfo.roles,
        },
        viewports,
        effectivePermissions: permissions,
        dataScope: "SELF",
        degraded: degradedFields.length > 0,
        degradedReason:
          degradedFields.length > 0 ? "DOWNSTREAM_PARTIAL_FAILURE" : null,
        degradedFields: degradedFields.length > 0 ? degradedFields : null,
      };
    },
  },
};
