import { Injectable, Inject, BadRequestException } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { WhmcsConnectionOrchestratorService } from "@bff/integrations/whmcs/connection/services/whmcs-connection-orchestrator.service";
import { getErrorMessage } from "@bff/core/utils/error.util";

/**
 * Shared Payment Validation Service
 *
 * Provides consistent payment method validation across order workflows.
 * Used by both OrderValidator and OrderFulfillmentValidator.
 */
@Injectable()
export class PaymentValidatorService {
  constructor(
    private readonly whmcs: WhmcsConnectionOrchestratorService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  /**
   * Validate that a payment method exists for the WHMCS client
   *
   * @param userId - User ID for logging purposes
   * @param whmcsClientId - WHMCS client ID to check
   * @throws BadRequestException if no payment method exists or verification fails
   */
  async validatePaymentMethodExists(userId: string, whmcsClientId: number): Promise<void> {
    try {
      const pay = await this.whmcs.getPaymentMethods({ clientid: whmcsClientId });
      const paymentMethods = Array.isArray(pay.paymethods) ? pay.paymethods : [];

      if (paymentMethods.length === 0) {
        this.logger.warn({ userId, whmcsClientId }, "No payment method on file");
        throw new BadRequestException("A payment method is required before ordering");
      }

      this.logger.log(
        { userId, whmcsClientId, count: paymentMethods.length },
        "Payment method verified"
      );
    } catch (e: unknown) {
      // Re-throw BadRequestException as-is
      if (e instanceof BadRequestException) {
        throw e;
      }

      const err = getErrorMessage(e);
      this.logger.error({ err, userId, whmcsClientId }, "Payment method verification failed");
      throw new BadRequestException("Unable to verify payment method. Please try again later.");
    }
  }
}
