import type { GraphqlContext } from "../context.js";
import type { ParentType, ViewportItemType } from "../types.js";
import type { ResolverDeps } from "./index.js";
import { mapParent, mapViewport } from "../../aggregation/response-mapper.js";
import { logger } from "../../shared/observability/logger.js";

/**
 * Me + Viewports Resolvers。
 *
 * - Query.me：返回家长个人信息（调 iam.getUserInfo 获取完整数据）
 * - Query.viewports：返回家长可见视口列表（调 iam.getViewports）
 *
 * 均使用 Promise.allSettled 降级：iam 失败时从 session 构造最小可用数据。
 */

export function buildMeQueryResolver(deps: ResolverDeps) {
  return async (
    _parent: unknown,
    _args: unknown,
    ctx: GraphqlContext,
  ): Promise<ParentType> => {
    try {
      const userInfo = await deps.iamClient.getUserInfo(ctx.session.parentId);
      return mapParent(userInfo);
    } catch (err) {
      logger.warn(
        { err, parentId: ctx.session.parentId },
        "iam.getUserInfo failed, using session fallback",
      );
      return {
        id: ctx.session.parentId,
        email: "",
        name: "",
        avatar: null,
        roles: ctx.session.roles,
        dataScope: "CHILDREN",
      };
    }
  };
}

export function buildViewportsQueryResolver(deps: ResolverDeps) {
  return async (
    _parent: unknown,
    _args: unknown,
    ctx: GraphqlContext,
  ): Promise<ViewportItemType[]> => {
    try {
      const viewports = await deps.iamClient.getViewports(ctx.session.parentId);
      return viewports.map(mapViewport);
    } catch (err) {
      logger.warn(
        { err, parentId: ctx.session.parentId },
        "iam.getViewports failed, returning empty",
      );
      return [];
    }
  };
}
