const axios = require("axios");

class ProtonPayPayoutService {
    constructor(config) {
        this.xKey = config.xKey;
        this.merchantCode = config.merchantCode;
        this.baseUrl = config.baseUrl || "";
    }
    // console.log("🚀 ~ ProtonPayPayoutService ~ constructor ~ config:")

    // Generate order ID for ProtonPay payout
    generateOrderId(prefix = "PPW") {
        return `${prefix}${Date.now()}${Math.floor(Math.random() * 1000)}`;
    }

    // Step 1: Initialize Payout
    async initializePayout(payoutData) {
        try {
            const {
                amount,
                userName,
                userId,
                phoneNumber,
                email,
                merchantOrderId,
                accountHolderName,
                accountNumber,
                bankName,
                ifscCode,
                returnUrl
            } = payoutData;

            const payload = {
                amount: Math.round(amount * 100), // Convert to paise for proton pay
                userName: String(userName),
                userId: String(userId),
                phoneNumber: String(phoneNumber),
                email: String(email),
                merchantCode: this.merchantCode,
                merchantOrderId: merchantOrderId,
                accountHolderName: String(accountHolderName),
                accountNumber: String(accountNumber),
                bankName: String(bankName),
                ifscCode: String(ifscCode),
                returnUrl: returnUrl || `${process.env.BASE_URL}/webhook/protonpay/payout`
            };

            console.log("ProtonPay Payout Initialize Request:", {
                url: `${this.baseUrl}/api/payouts/initiate`,
                payload: payload
            });

            const response = await axios.post(
                `${this.baseUrl}/api/payouts/initiate`,
                payload,
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Key': this.xKey,
                        'Accept': 'application/json'
                    },
                    timeout: 15000
                }
            );

            console.log("ProtonPay Payout Initialize Response:", response.data);

            if (response.status === 201) {
                return {
                    success: true,
                    payoutId: response.data.payoutId,
                    merchantOrderId: merchantOrderId,
                    amount: response.data.amount,
                    gatewayResponse: response.data
                };
            }

            return {
                success: false,
                error: response.data,
                gatewayResponse: response.data
            };

        } catch (error) {
            console.error("ProtonPay Payout Initialize Error:", error.response?.data || error.message);
            return {
                success: false,
                error: error.response?.data || error.message,
                statusCode: error.response?.status,
                gatewayResponse: error.response?.data
            };
        }
    }

    // Step 2: Check Payout Status
    async checkPayoutStatus(merchantOrderId, payoutId) {
        try {
            const payload = {
                merchantCode: this.merchantCode,
                merchantOrderId: merchantOrderId,
                payoutId: payoutId
            };

            const response = await axios.post(
                `${this.baseUrl}/api/payouts/checkStatus`,
                payload,
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Key': this.xKey,
                        'Accept': 'application/json'
                    },
                    timeout: 10000
                }
            );

            console.log("ProtonPay Payout Status Response:", response.data);

            return {
                success: true,
                status: response.data.status,
                gatewayResponse: response.data
            };

        } catch (error) {
            console.error("ProtonPay Payout Status Error:", error.response?.data || error.message);
            return {
                success: false,
                error: error.response?.data || error.message,
                gatewayResponse: error.response?.data
            };
        }
    }
}

module.exports = ProtonPayPayoutService;