import type { GraphqlContext } from "../context.js";
import type { GradePageType } from "../types.js";
import type { ResolverDeps } from "./index.js";
import { mapGrade } from "../../aggregation/response-mapper.js";

/**
 * Grade Resolver（对齐 workline P4.5）。
 *
 * Query.childGrades：孩子成绩分页查询。
 *
 * - 先 ChildGuard 校验 childId ∈ 家长绑定列表
 * - 再调 core-edu.listGradesByStudent 获取成绩
 * - 支持 subject 过滤 + page / pageSize 分页
 * - pageSize 上限 50（防止过大查询）
 *
 * 注意：proto Grade.score 为 string，response-mapper 负责 Number.parseFloat 转换。
 */
const MAX_PAGE_SIZE = 50;

export function buildChildGradesQueryResolver(deps: ResolverDeps) {
  return async (
    _parent: unknown,
    args: {
      childId: string;
      page?: number;
      pageSize?: number;
      subject?: string;
    },
    ctx: GraphqlContext,
  ): Promise<GradePageType> => {
    await deps.childGuard.validateChildAccess(
      ctx.session.parentId,
      args.childId,
    );

    const grades = await ctx.loaders.grades.load(args.childId);
    const mapped = grades.map(mapGrade);

    const filtered = args.subject
      ? mapped.filter((g) => g.subject === args.subject)
      : mapped;

    const page = Math.max(1, args.page ?? 1);
    const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(1, args.pageSize ?? 20));
    const start = (page - 1) * pageSize;
    const items = filtered.slice(start, start + pageSize);

    return {
      items,
      pagination: { page, pageSize, total: filtered.length },
    };
  };
}
