// const user_module = require("../model/user_module")
// const wallet_trans_history_module = require("../model/wallet_trans_history_module")

// const deductUserCloseWallet = async (token) => {
//     try {
//         const result = await wallet_trans_history_module.find({ open_result_token: token })
//         if (result.length <= 0) {
//             return
//         }
//         await Promise.all(result.map(async (item) => {
//             const user_id = item.userDB_id
//             const tx = item.tx_request_number
//             const amount = item.amount
//             await user_module.findByIdAndUpdate(user_id, { wallet_balance: { $inc: -amount } })
//             await wallet_trans_history_module.deleteOne({ userDB_id: user_id, tx_request_number: tx })
//         }))
//     } catch (error) {
//         console.log("error in the user deduct wallet 21", error)
//     }
// }

// module.export = deductUserCloseWallet


// refundUtils.js
const user_module = require("../model/user_module");
const wallet_trans_history_module = require("../model/wallet_trans_history_module");

const refundStarlineWinnings = async (open_result_token, session = null) => {
    try {
        console.log(`🔍 Processing refunds for token: ${open_result_token}`);
        
        // Find all wallet transactions for this result token
        const walletTransactions = await wallet_trans_history_module.find({ 
            open_result_token: open_result_token 
        });

        console.log(`📊 Found ${walletTransactions.length} wallet transactions to refund`);

        if (walletTransactions.length === 0) {
            console.log("ℹ️ No wallet transactions found to refund");
            return { success: true, refundedCount: 0 };
        }

        let refundedCount = 0;

        // Process each transaction
        for (const transaction of walletTransactions) {
            try {
                const user_id = transaction.userDB_id;
                const amount = transaction.amount;
                const tx_number = transaction.tx_request_number;

                console.log(`💸 Refunding ${amount} to user ${user_id}`);

                // Deduct from user wallet
                await user_module.findByIdAndUpdate(
                    user_id,
                    { $inc: { wallet_balance: -amount } },
                    { session }
                );

                // Delete the wallet transaction record
                await wallet_trans_history_module.deleteOne(
                    { _id: transaction._id },
                    { session }
                );

                refundedCount++;
                console.log(`✅ Successfully refunded user ${user_id}`);

            } catch (userError) {
                console.error(`❌ Failed to refund user ${transaction.userDB_id}:`, userError);
                // Continue with other users
            }
        }

        console.log(`✅ Completed refunds for ${refundedCount} users`);
        return { success: true, refundedCount };

    } catch (error) {
        console.error("❌ Error in refundStarlineWinnings:", error);
        throw error;
    }
};

module.exports = { refundStarlineWinnings };