import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  HttpException,
  HttpStatus,
} from "@nestjs/common";
import type { Request } from "express";
import { Logger } from "nestjs-pino";
import { SalesforceRequestQueueService } from "@bff/core/queue/services/salesforce-request-queue.service";

@Injectable()
export class SalesforceReadThrottleGuard implements CanActivate {
  constructor(
    private readonly queue: SalesforceRequestQueueService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const state = this.queue.getDegradationState();
    if (!state.degraded) {
      return true;
    }

    const request = context.switchToHttp().getRequest<Request>();
    this.logger.warn("Throttling Salesforce-backed read due to degraded state", {
      path: request?.originalUrl ?? request?.url,
      reason: state.reason,
      cooldownExpiresAt: state.cooldownExpiresAt,
      usagePercent: state.usagePercent,
    });

    throw new HttpException(
      "We're experiencing high load right now. Please try again in a moment.",
      HttpStatus.TOO_MANY_REQUESTS
    );
  }
}
