import crypto from 'crypto';
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 PhonePeGateway implements IPaymentGateway {
  private merchantId: string;
  private saltKey: string;
  private saltIndex: string;

  constructor(config?: any) {
    this.merchantId = config?.merchantId || process.env.PHONEPE_MERCHANT_ID || 'MOCK_MERCHANT_ID';
    this.saltKey = config?.saltKey || process.env.PHONEPE_SALT_KEY || 'mock_salt_key';
    this.saltIndex = config?.saltIndex || process.env.PHONEPE_SALT_INDEX || '1';
  }

  async createOrder(order: any): Promise<PaymentGatewayOrder> {
    const txnId = `ppe_txn_${Date.now()}_${Math.floor(100 + Math.random() * 900)}`;
    return {
      id: order.id,
      gatewayOrderId: txnId,
      amount: Number(order.grandTotal),
      currency: 'INR',
      status: 'CREATED',
    };
  }

  async createCheckout(checkout: any): Promise<PaymentGatewayCheckout> {
    // Generate X-VERIFY checksum for Merchant API payload
    const payload = {
      merchantId: this.merchantId,
      merchantTransactionId: checkout.gatewayOrderId,
      merchantUserId: `usr_${checkout.id}`,
      amount: Math.round(checkout.amount * 100),
      redirectUrl: `${process.env.APP_URL || 'http://localhost:3000'}/payment/callback/phonepe`,
      redirectMode: 'POST',
      paymentInstrument: { type: 'PAY_PAGE' },
    };

    const base64Payload = Buffer.from(JSON.stringify(payload)).toString('base64');
    const checksum = crypto
      .createHash('sha256')
      .update(base64Payload + '/pg/v1/pay' + this.saltKey)
      .digest('hex') + '###' + this.saltIndex;

    logger.info(`[PhonePeGateway] Generated checksum: ${checksum}`);

    return {
      checkoutUrl: `https://merchants.phonepe.com/outer/v1/pay?payload=${base64Payload}&verify=${checksum}`,
      gatewayTransactionId: checkout.gatewayOrderId,
    };
  }

  async verifyPayment(payload: any): Promise<PaymentGatewayVerify> {
    const transactionId = payload.merchantTransactionId || payload.transactionId;
    const responseCode = payload.code || 'SUCCESS';
    const isSuccess = responseCode === 'SUCCESS' || responseCode === 'PAYMENT_SUCCESS';

    return {
      success: isSuccess,
      status: isSuccess ? 'SUCCESS' : 'FAILED',
      gatewayPaymentId: payload.providerReferenceId || `ppe_ref_${Date.now()}`,
      gatewayTransactionId: transactionId,
      message: `PhonePe checkout verified status: ${responseCode}`,
      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 = `ppe_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> {
    // Verify phonepe signature if passed
    return {
      event: 'payment.success',
      orderId: payload.merchantTransactionId,
      paymentId: payload.providerReferenceId,
      status: 'SUCCESS',
    };
  }

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

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