import { Api } from '@aurorajs.dev/core-back';
import { ExecutionContext, Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';

/**
 * `ThrottlerGuard` variant for GraphQL resolvers. The stock guard reads the request/response
 * via `context.switchToHttp()`, which is empty under a GraphQL execution context. This override
 * resolves them with the project's canonical `Api.getRequestFromExecutionContext` (the same
 * helper `AuthenticationJwtGuard` uses) — the Apollo context exposes `req` via
 * `context: ({ req }) => ({ req })` in `graphql-config.module.ts`, and Express attaches the
 * response as `req.res` (used by the throttler to set the `Retry-After` header).
 */
@Injectable()
export class GqlThrottlerGuard extends ThrottlerGuard {
  protected getRequestResponse(context: ExecutionContext): {
    req: Record<string, any>;
    res: Record<string, any>;
  } {
    const req = Api.getRequestFromExecutionContext<Record<string, any>>(context);
    return { req, res: req.res };
  }
}
