const DollarBazarPayoutService = require('./dollarbazar.payout.service');
const ProtonPaySettings = require('../model/ProtonPaySettings');
const ProtonPayPayoutService = require('./protonpay.payout.service');

class PayoutManager {
    constructor() {
        this.dollarBazarService = DollarBazarPayoutService;
    }

    // Get ProtonPay payout service instance
    async getProtonPayService() {
        try {
            const protonPayConfig = await ProtonPaySettings.findOne({ gatewayId: 'proton_pay' }).lean();
            console.log("🚀 ~ PayoutManager ~ getProtonPayService ~ protonPayConfig:", protonPayConfig)

            if (!protonPayConfig || !protonPayConfig.baseUrl || !protonPayConfig.merchantKey || !protonPayConfig.merchantCode) {
                console.log("not found details in proton pay config await")
                return null;
            }

            return new ProtonPayPayoutService({
                // xKey: protonPayConfig.xKey,
                xKey: protonPayConfig.merchantKey,
                merchantCode: protonPayConfig.merchantCode,
                baseUrl: protonPayConfig.baseUrl || ''
            });
        } catch (error) {
            console.error("Error getting ProtonPay service:", error);
            return null;
        }
    }

    // Process payout based on payment method
    async processPayout(amount, bankDetails, orderId, paymentMethod) {
        try {            // paymentMethod: 7 = DollarBazar, 8 = ProtonPay



            if (paymentMethod === 7) {
                // DollarBazar payout
                const payoutResult = await this.dollarBazarService.doPayout(amount, bankDetails, orderId);
                return {
                    gateway: 'DOLLARBAZAR',
                    ...payoutResult
                };
            } else if (paymentMethod === 8) {
                // ProtonPay payout
                const protonPayService = await this.getProtonPayService();
                console.log("🚀 ~ PayoutManager ~ processPayout ~ protonPayService:", protonPayService)

                if (!protonPayService) {
                    throw new Error("ProtonPay payout service not configured or disabled");
                }

                const payoutData = {
                    amount: amount,
                    userName: bankDetails.ac_holder_name || "User",
                    userId: bankDetails.userDB_id?.toString() || "user_" + Date.now(),
                    phoneNumber: bankDetails.mobile_number || "9999999999",
                    email: bankDetails.email || "user@example.com",
                    merchantOrderId: orderId,
                    accountHolderName: bankDetails.ac_holder_name,
                    accountNumber: bankDetails.ac_number,
                    bankName: bankDetails.bank_name,
                    ifscCode: bankDetails.ifsc_code,
                    returnUrl: `https://api.al786.com/admin/webhook/protonpay/payout`
                };

                const payoutResult = await protonPayService.initializePayout(payoutData);

                if (!payoutResult.success) {
                    return {
                        status: "FAILED",
                        message: payoutResult.error?.message || "ProtonPay payout initialization failed",
                        gateway: 'PROTONPAY',
                        gatewayResponse: payoutResult.gatewayResponse
                    };
                }

                return {
                    status: "INITIATED",
                    message: "Payout initiated successfully",
                    gateway: 'PROTONPAY',
                    payoutId: payoutResult.payoutId,
                    merchantOrderId: payoutResult.merchantOrderId,
                    gatewayResponse: payoutResult.gatewayResponse
                };
            } else {
                throw new Error(`Unsupported payment method: ${paymentMethod}`);
            }
        } catch (error) {
            console.error("Payout processing error:", error);
            return {
                status: "FAILED",
                message: error.message,
                gateway: paymentMethod === 8 ? 'PROTONPAY' : 'DOLLARBAZAR'
            };
        }
    }

    // Check payout status
    async checkPayoutStatus(orderId, payoutId, paymentMethod = 7) {
        try {
            if (paymentMethod === 7) {
                // DollarBazar status check
                const authTokens = await this.dollarBazarService.getAuthTokens(0, orderId);
                if (!authTokens.api_token || !authTokens.id_token) {
                    return { success: false, error: "Authentication failed" };
                }

                const statusResult = await this.dollarBazarService.checkPayoutStatus(
                    authTokens.api_token,
                    authTokens.id_token,
                    orderId
                );
                return { gateway: 'DOLLARBAZAR', ...statusResult };
            } else if (paymentMethod === 8) {
                // ProtonPay status check
                const protonPayService = await this.getProtonPayService();
                if (!protonPayService) {
                    return { success: false, error: "ProtonPay service not available" };
                }

                const statusResult = await protonPayService.checkPayoutStatus(orderId, payoutId);
                return { gateway: 'PROTONPAY', ...statusResult };
            }

            return { success: false, error: "Unsupported payment method" };
        } catch (error) {
            console.error("Check payout status error:", error);
            return { success: false, error: error.message };
        }
    }
}

module.exports = new PayoutManager();