import { IPaymentGateway } from '../interfaces/payment-gateway.interface';
import {
  PaymentGatewayOrder,
  PaymentGatewayCheckout,
  PaymentGatewayVerify,
  PaymentGatewayCapture,
  PaymentGatewayRefund,
  PaymentGatewayStatus,
} from '../dto/payment.dto';
import { logger } from '../../../config/logger';

export class DynamicUpiGateway implements IPaymentGateway {
  private merchantVpa: string;
  private merchantName: string;

  constructor(config?: any) {
    this.merchantVpa = config?.merchantId || process.env.UPI_MERCHANT_ID || 'indianbooks@okaxis';
    this.merchantName = config?.merchantName || process.env.UPI_MERCHANT_NAME || 'Indian Books Worldwide';
  }

  async createOrder(order: any): Promise<PaymentGatewayOrder> {
    const upiOrderId = `upi_ord_${Date.now()}`;
    return {
      id: order.id,
      gatewayOrderId: upiOrderId,
      amount: Number(order.grandTotal),
      currency: 'INR',
      status: 'CREATED',
    };
  }

  async createCheckout(checkout: any): Promise<PaymentGatewayCheckout> {
    // Generate UPI Intent URL: upi://pay?pa=merchantVpa&pn=merchantName&tr=txnId&am=amount&cu=INR&tn=BookPurchase
    const transactionId = checkout.gatewayOrderId;
    const amount = checkout.amount;
    const intentUrl = `upi://pay?pa=${encodeURIComponent(this.merchantVpa)}&pn=${encodeURIComponent(this.merchantName)}&tr=${encodeURIComponent(transactionId)}&am=${amount}&cu=INR&tn=IndianBooksPurchase`;

    // Static Mock QR Code Data representing the deep link (Base64 placeholder string for a beautiful QR image)
    const base64QrPlaceholder = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';

    logger.info(`[DynamicUpiGateway] Created UPI Intent deep link: ${intentUrl}`);

    return {
      checkoutUrl: intentUrl,
      gatewayTransactionId: transactionId,
      qrCodeData: base64QrPlaceholder,
      intentUrl,
    };
  }

  async verifyPayment(payload: any): Promise<PaymentGatewayVerify> {
    const isSuccess = payload.status === 'success' || payload.status === 'SUCCESS';
    return {
      success: isSuccess,
      status: isSuccess ? 'SUCCESS' : 'PENDING',
      gatewayPaymentId: payload.approvalRefNo || `upi_ref_${Date.now()}`,
      gatewayTransactionId: payload.txnId,
      message: isSuccess ? 'UPI Transaction Success' : 'UPI Transaction Awaiting Settlement',
      rawResponse: payload,
    };
  }

  async capturePayment(paymentId: string, amount: number): Promise<PaymentGatewayCapture> {
    return {
      success: true,
      gatewayPaymentId: paymentId,
      amount,
      status: 'SUCCESS',
    };
  }

  async refundPayment(transactionId: string, amount: number, reason?: string): Promise<PaymentGatewayRefund> {
    const refundId = `upi_ref_${Date.now()}`;
    return {
      success: true,
      gatewayRefundId: refundId,
      amount,
      status: 'SUCCESS',
    };
  }

  async paymentStatus(transactionId: string): Promise<PaymentGatewayStatus> {
    return {
      status: 'SUCCESS',
      gatewayTransactionId: transactionId,
    };
  }

  async handleCallback(payload: any): Promise<any> {
    return this.verifyPayment(payload);
  }

  async handleWebhook(payload: any, signature?: string): Promise<any> {
    return {
      event: 'payment.success',
      orderId: payload.txnId,
      paymentId: payload.approvalRefNo,
      status: 'SUCCESS',
    };
  }

  async generateReceipt(paymentId: string): Promise<any> {
    return { receiptId: `upi_rcpt_${paymentId}` };
  }

  async cancelPayment(paymentId: string): Promise<any> {
    return { success: true };
  }
}
