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

export abstract class SalesforceThrottleBaseGuard implements CanActivate {
  protected abstract readonly operationType: string;
  protected abstract readonly userMessage: string;

  constructor(
    protected readonly queue: SalesforceRequestQueueService,
    @Inject(Logger) protected 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 ${this.operationType} due to degraded state`, {
      path: request?.originalUrl ?? request?.url,
      reason: state.reason,
      cooldownExpiresAt: state.cooldownExpiresAt,
      usagePercent: state.usagePercent,
    });

    throw new HttpException(this.userMessage, HttpStatus.TOO_MANY_REQUESTS);
  }
}
