import { Injectable } from '@nestjs/common';
import { createHash } from 'crypto';

@Injectable()
export class BancardTokenService {
  generateSingleBuyToken(privateKey: string, shopProcessId: bigint, amount: number, currency: string): string {
    const raw = `${privateKey}${shopProcessId}${amount.toFixed(2)}${currency}`;
    return createHash('md5').update(raw).digest('hex');
  }

  generateRollbackToken(privateKey: string, shopProcessId: bigint): string {
    const raw = `${privateKey}${shopProcessId}rollback`;
    return createHash('md5').update(raw).digest('hex');
  }

  generateRefundToken(privateKey: string, shopProcessId: bigint, amount: number, currency: string): string {
    const raw = `${privateKey}${shopProcessId}refund${amount.toFixed(2)}${currency}`;
    return createHash('md5').update(raw).digest('hex');
  }

  generateConfirmationsToken(privateKey: string, shopProcessId: bigint): string {
    const raw = `${privateKey}${shopProcessId}get_confirmation`;
    return createHash('md5').update(raw).digest('hex');
  }

  /**
   * Token que Bancard incluye en el webhook de confirmación de pago:
   * md5(private_key + shop_process_id + "confirm" + amount + currency).
   * Se usa para verificar que el webhook entrante proviene realmente de Bancard.
   */
  generateConfirmationWebhookToken(
    privateKey: string,
    shopProcessId: bigint,
    amount: number,
    currency: string,
  ): string {
    const raw = `${privateKey}${shopProcessId}confirm${amount.toFixed(2)}${currency}`;
    return createHash('md5').update(raw).digest('hex');
  }
}
