/**
 * Classes Resolver - myClasses Query.
 *
 * 仲裁依据:
 *   - student-bff.schema.graphql Query.myClasses
 *   - coord-final-decisions §2 B2 (gRPC 调用 core-edu)
 */
import type { StudentBffContext } from "../../shared/graphql/yoga.js";
import { ok, fail } from "../../shared/action-state.js";
import { UnauthorizedError } from "../../shared/errors/application-error.js";

export const classesResolvers = {
  Query: {
    /**
     * myClasses: 我所在班级列表.
     * @permission STUDENT_DASHBOARD_READ
     * @dataScope OWN
     */
    async myClasses(
      _parent: unknown,
      _args: unknown,
      ctx: StudentBffContext,
    ): Promise<unknown> {
      if (!ctx.userId) {
        throw new UnauthorizedError();
      }

      try {
        const result = await ctx.downstream.call("core-edu", "GetClassesByStudent", {
          studentId: ctx.userId,
        }, {
          traceId: ctx.traceId,
          metadata: { "x-user-id": ctx.userId },
        });

        const data = result as { classes: unknown[] };
        return ok(data, { traceId: ctx.traceId });
      } catch (err) {
        return fail(
          "BFF_STUDENT_BAD_GATEWAY",
          `Failed to fetch classes: ${(err as Error).message}`,
          { i18nKey: "error.bffStudent.bad_gateway", traceId: ctx.traceId },
        );
      }
    },
  },
};
