"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PhonePeGateway = void 0;
const crypto_1 = __importDefault(require("crypto"));
const logger_1 = require("../../../config/logger");
class PhonePeGateway {
    merchantId;
    saltKey;
    saltIndex;
    constructor(config) {
        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) {
        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) {
        // 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_1.default
            .createHash('sha256')
            .update(base64Payload + '/pg/v1/pay' + this.saltKey)
            .digest('hex') + '###' + this.saltIndex;
        logger_1.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) {
        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, amount) {
        return {
            success: true,
            gatewayPaymentId: paymentId,
            amount,
            status: 'SUCCESS',
        };
    }
    async refundPayment(transactionId, amount, reason) {
        const refundId = `ppe_ref_${Date.now()}`;
        return {
            success: true,
            gatewayRefundId: refundId,
            amount,
            status: 'SUCCESS',
        };
    }
    async paymentStatus(transactionId) {
        return {
            status: 'SUCCESS',
            gatewayTransactionId: transactionId,
        };
    }
    async handleCallback(payload) {
        return this.verifyPayment(payload);
    }
    async handleWebhook(payload, signature) {
        // Verify phonepe signature if passed
        return {
            event: 'payment.success',
            orderId: payload.merchantTransactionId,
            paymentId: payload.providerReferenceId,
            status: 'SUCCESS',
        };
    }
    async generateReceipt(paymentId) {
        return { receiptId: `ppe_rcpt_${paymentId}` };
    }
    async cancelPayment(paymentId) {
        return { success: true };
    }
}
exports.PhonePeGateway = PhonePeGateway;
//# sourceMappingURL=phonepe.gateway.js.map