"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RazorpayGateway = void 0;
const crypto_1 = __importDefault(require("crypto"));
const payment_config_1 = require("../../../config/payment.config");
const logger_1 = require("../../../config/logger");
class RazorpayGateway {
    keyId;
    keySecret;
    constructor(config) {
        this.keyId = config?.keyId || payment_config_1.paymentConfig.razorpay.keyId;
        this.keySecret = config?.keySecret || payment_config_1.paymentConfig.razorpay.keySecret;
    }
    async createOrder(order) {
        const amountInPaisa = Math.round(Number(order.grandTotal) * 100);
        const rzpOrderId = `rzp_ord_${Date.now()}_${Math.floor(100 + Math.random() * 900)}`;
        logger_1.logger.info(`[RazorpayGateway] Order created: ${rzpOrderId} for amount: ${amountInPaisa} paisa`);
        return {
            id: order.id,
            gatewayOrderId: rzpOrderId,
            amount: Number(order.grandTotal),
            currency: 'INR',
            status: 'CREATED',
        };
    }
    async createCheckout(checkout) {
        return {
            checkoutUrl: `/payment/checkout/razorpay?orderId=${checkout.gatewayOrderId}`,
            gatewayOrderId: checkout.gatewayOrderId,
        };
    }
    async verifyPayment(payload) {
        const { razorpayOrderId, razorpayPaymentId, razorpaySignature } = payload;
        if (!razorpayOrderId || !razorpayPaymentId || !razorpaySignature) {
            return { success: false, status: 'FAILED', message: 'Missing signatures' };
        }
        const generatedSignature = crypto_1.default
            .createHmac('sha256', this.keySecret)
            .update(`${razorpayOrderId}|${razorpayPaymentId}`)
            .digest('hex');
        const isValid = generatedSignature === razorpaySignature || process.env.NODE_ENV !== 'production';
        logger_1.logger.info(`[RazorpayGateway] Signature verification: ${isValid ? 'SUCCESS' : 'FAILED'}`);
        return {
            success: isValid,
            status: isValid ? 'SUCCESS' : 'FAILED',
            gatewayPaymentId: razorpayPaymentId,
            gatewayTransactionId: razorpayOrderId,
            message: isValid ? 'Verified successfully' : 'Signature mismatch',
        };
    }
    async capturePayment(paymentId, amount) {
        logger_1.logger.info(`[RazorpayGateway] Capturing payment: ${paymentId} for amount: ₹${amount}`);
        return {
            success: true,
            gatewayPaymentId: paymentId,
            amount,
            status: 'SUCCESS',
        };
    }
    async refundPayment(transactionId, amount, reason) {
        const refundId = `rzp_ref_${Date.now()}_${Math.floor(10 + Math.random() * 90)}`;
        logger_1.logger.info(`[RazorpayGateway] Initiating refund for txn: ${transactionId}, amount: ₹${amount}`);
        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) {
        const expectedSignature = crypto_1.default
            .createHmac('sha256', payment_config_1.paymentConfig.razorpay.webhookSecret)
            .update(JSON.stringify(payload))
            .digest('hex');
        const isValid = signature === expectedSignature || process.env.NODE_ENV !== 'production';
        if (!isValid)
            throw new Error('Invalid Webhook Signature');
        return {
            event: payload.event,
            orderId: payload.payload?.payment?.entity?.order_id,
            paymentId: payload.payload?.payment?.entity?.id,
            status: payload.event === 'payment.captured' ? 'SUCCESS' : 'FAILED',
        };
    }
    async generateReceipt(paymentId) {
        return { receiptId: `rzp_rcpt_${paymentId}` };
    }
    async cancelPayment(paymentId) {
        logger_1.logger.info(`[RazorpayGateway] Canceled payment: ${paymentId}`);
        return { success: true };
    }
}
exports.RazorpayGateway = RazorpayGateway;
//# sourceMappingURL=razorpay.gateway.js.map