// GraphQL 错误格式化（G8 裁决：ActionState 信封 + BFF_TEACHER_ 错误码）
// Yoga 自身错误处理，extensions.code = BFF_TEACHER_* + extensions.traceId
import { ApplicationError } from "../shared/errors/application-error.js";

/**
 * 格式化 GraphQL 错误（president §2.6 降级模式 B + G8 ActionState 信封）
 * 错误 extensions 包含：code（BFF_TEACHER_*）、traceId、details
 */
export function formatGraphQLError(
  error: unknown,
  traceId?: string,
): { message: string; extensions: Record<string, unknown> } {
  // ApplicationError → 映射 code + details
  if (error instanceof ApplicationError) {
    return {
      message: error.message,
      extensions: {
        code: error.code,
        traceId: traceId ?? error.traceId ?? "unknown",
        details: error.details,
      },
    };
  }

  // 原生 GraphQL Error（语法错误、校验错误等）
  const err = error as {
    message?: string;
    extensions?: Record<string, unknown>;
  };
  return {
    message: err.message ?? "Unknown GraphQL error",
    extensions: {
      code: (err.extensions?.code as string) ?? "BFF_TEACHER_INTERNAL_ERROR",
      traceId: traceId ?? "unknown",
    },
  };
}
