const admin_module = require("../model/admin_module");
const add_funds_module = require("../model/add_funds_module");
const user_module = require("../model/user_module");
const wallet_trans_history_module = require("../model/wallet_trans_history_module");
const withdraw_fund_request_module = require("../model/withdraw_fund_request_module")

async function dollarbazarWebhook(req, res) {
  try {
    const payload = req.body || {};
    console.log("💠 DollarBazar Webhook Received:", payload);

    const {
      amount,
      transaction_status,
      transactionId,
      bankReference,
      orderId,
      merchant_reference
    } = payload;

    const merchantOrderId = orderId;

    if (!merchantOrderId) {
      console.log("❌ Webhook missing orderId");
      return res.status(400).send("orderId missing");
    }

    const deposit = await add_funds_module.findOne({
      tx_request_number: merchantOrderId
    });

    if (!deposit) {
      console.log("⚠ No deposit entry found:", merchantOrderId);
      // return res.status(200).send("no-entry");
      return res.status(200).json({ success: false, msg: "no-entry" });
    }

    if (deposit.fund_status === 1) {
      console.log("⚠ Already processed:", merchantOrderId);
      return res.status(200).json({ success: false, msg: "already-processed" });
    }

    if (String(transaction_status).toUpperCase() === "SUCCESS") {
      const user = await user_module.findById(deposit.userDB_id);

      user.wallet_balance =
        Number(user.wallet_balance || 0) + Number(deposit.amount);
      await user.save();

      deposit.fund_status = 1;
      deposit.txn_ref = transactionId;
      deposit.bankReference = bankReference;
      await deposit.save();

      const adminData = await admin_module.findOne({ admin_type: 0 });
      if (!adminData) {
        console.log("❌ Admin data not found for wallet update");
        return res.status(500).json({ success: false, msg: "Admin data not found" });
      }

      adminData.wallet_amount =
        Number(adminData?.wallet_amount || 0) - Number(deposit?.amount);
      await adminData.save();



      await wallet_trans_history_module.create({
        userDB_id: user._id,
        amount: Number(amount || deposit.amount),
        before_wallet: Number(user.wallet_balance || 0),
        transaction_type: 1, // 1 on deposit/add fund    2 on withdraw fund
        transaction_note: "UPI Auto Deposit - DollarBazar",
        amount_status: 19,
        txn_ref: transactionId,
        tx_request_number: merchantOrderId,
        admin_name: adminData?.username,
        admin_type: adminData?.admin_type
      });

      console.log("✅ Payment success updated:", merchantOrderId);
    } else if (String(transaction_status).toUpperCase() === "FAIL") {
      deposit.fund_status = 2;
      deposit.txn_ref = transactionId;
      await deposit.save();
    }

    return res.status(200).json({ success: true, msg: "OK" });
  } catch (err) {
    console.error("❌ Webhook Error:", err);
    return res.status(500).send("ERR");
  }
}

async function dollarbazarPayoutWebhook(req, res) {
  try {
    const body = req.body || {};
    console.log("💠 DollarBazar Webhook Payload:", body);

    let payout = body.successPayout || body.failPayout;
    if (!payout) {
      console.log("⚠ Invalid webhook payload");
      return res.status(400).send("Invalid payload");
    }

    const orderId = payout.orderId;
    const status = payout.status;
    const txnId = payout.txnId;
    const bankRefId = payout.bankRefId || null;

    if (!orderId) return res.status(400).send("orderId missing");

    const withdraw = await withdraw_fund_request_module.findOne({
      tx_request_number: orderId
    });

    if (!withdraw) {
      console.log("⚠ Withdraw request not found:", orderId);
      return res.status(200).send("Withdraw request not found");
    }

    if (withdraw.fund_status === 1) {
      console.log("⚠ Already processed:", orderId);
      return res.status(200).send("already processed");
    }

    // SUCCESS
    if (body.success === true && body.successPayout) {
      const user = await user_module.findById(withdraw.userDB_id);

      const before_wallet = user.wallet_balance;

      user.wallet_balance = Number(user.wallet_balance) - Number(withdraw.amount);
      await user.save();

      withdraw.fund_status = 1;
      withdraw.gateway_txn_id = txnId;
      withdraw.bankReference = bankRefId;
      withdraw.remark = "Payout Success";
      withdraw.payment_method = 7;
      await withdraw.save();

      await wallet_trans_history_module.create({
        userDB_id: user._id,
        amount: Number(withdraw.amount),
        before_wallet,
        transaction_type: 2,
        transaction_note: "Payout Success via DollarBazar",
        tx_request_number: orderId,
        txn_id: txnId,
        txn_ref: bankRefId,
        status: "SUCCESS",
        payby: "Admin"
      });

      console.log("✅ SUCCESS updated:", orderId);
    }

    // FAILED
    else if (body.success === true && body.failPayout) {
      withdraw.fund_status = 2;
      withdraw.gateway_txn_id = txnId;
      withdraw.remark = "Payout Failed";
      await withdraw.save();

      console.log("❌ FAILED updated:", orderId);
    }

    return res.status(200).send("OK");
  } catch (e) {
    console.error("❌ Webhook Error:", e);
    res.status(500).send("ERR");
  }
}


async function protonpayWebhook(req, res) {
  try {
    const payload = req.body;

    console.log("ProtonPay Webhook Received:", payload);

    // Verify webhook signature (add if ProtonPay provides)
    // const signature = req.headers['x-signature'];
    // if (!verifySignature(payload, signature)) {
    //   return res.status(401).json({ success: false, msg: "Invalid signature" });
    // }

    const status = payload.status;
    const orderId = payload.merchantOrderId;
    const payinId = payload.payinId;

    if (!orderId) {
      return res.status(400).json({ success: false, msg: "Invalid payload: missing orderId" });
    }

    // Find transaction
    const transaction = await add_funds_module.findOne({
      tx_request_number: orderId,
      payment_method: 'PROTONPAY'
    });
    console.log("🚀 ~ protonpayWebhook ~ transaction:", transaction)

    if (!transaction) {
      console.error(`Transaction not found for orderId: ${orderId}`);
      return res.status(404).json({ success: false, msg: "Transaction not found" });
    }

    let newFundStatus = transaction.fund_status;
    let updateData = {
      gateway_raw_response: payload,
      updated_at: new Date()
    };

    // Map ProtonPay status
    if (status === 'success' || status === 'SUCCESS') {
      newFundStatus = 1; // Approved
      updateData.fund_status = 1;
      updateData.txn_ref = payinId;
    } else if (status === 'failed' || status === 'FAILED' || status === 'rejected') {
      newFundStatus = 2; // Failed
      updateData.fund_status = 2;
    }
    // If pending, keep as pending (0)

    // Update transaction
    await add_funds_module.findByIdAndUpdate(transaction._id, updateData);

    // Credit wallet if status changed to approved
    if (newFundStatus === 1 && transaction.fund_status !== 1) {
      const user = await user_module.findById(transaction.userDB_id);
      if (user) {
        const before_wallet = user?.wallet_balance;
        user.wallet_balance += transaction.amount;
        await user.save();

        await wallet_trans_history_module.create({
          userDB_id: user._id,
          amount: transaction.amount,
          before_wallet: before_wallet,
          transaction_type: 1,
          transaction_note: `Deposit via ProtonPay ${orderId}`,
          amount_status: 19,
          tx_request_number: `WTH${Date.now()}`,
          txn_ref: payinId
        });

        console.log(`Wallet credited via ProtonPay webhook for order ${orderId}`);
      }
    }

    return res.json({ success: true, msg: "Webhook processed" });

  } catch (error) {
    console.error("ProtonPay Webhook Error:", error);
    return res.status(500).json({
      success: false,
      msg: "Failed to process webhook",
      error: error.message
    });
  }
}

async function protonPayPayoutWebhook(req, res){
    try {
        const payload = req.body;
        console.log("ProtonPay Payout Webhook:", payload);

        const { status, merchantOrderId, payoutId } = payload;

        if (!merchantOrderId) {
            return res.status(400).json({ success: false, msg: "Invalid payload" });
        }

        // Find withdraw request
        const withdrawRequest = await withdraw_fund_request_module.findOne({ 
            tx_request_number: merchantOrderId,
            payment_method: 8 // ProtonPay
        });

        if (!withdrawRequest) {
            console.error(`Withdraw request not found: ${merchantOrderId}`);
            return res.json({ success: true, msg: "Request not found" });
        }

        // Update based on webhook status
        if (status === 'success') {
            // Success - update if needed
            withdrawRequest.remark = "Payout completed successfully via webhook";
            withdrawRequest.utr = payload.paymentId || payoutId;
            await withdrawRequest.save();

            await wallet_trans_history_module.create({
                userDB_id: user._id,
                amount: record.amount,
                transaction_type: 2,
                transaction_note: `Withdraw via ${payment_method === 7 ? 'DollarBazar' : 'ProtonPay'} Payout`,
                utr: utr,
                status: "SUCCESS"
            });


        } else if (status === 'failed') {
            // Failed - refund user
            withdrawRequest.fund_status = 2;
            withdrawRequest.remark = "Payout failed via webhook";
            await withdrawRequest.save();
            
            // Refund user wallet
            const user = await user_module.findById(withdrawRequest.userDB_id);
            if (user) {
                user.wallet_balance += withdrawRequest.amount;
                await user.save();
            }
        }

        return res.json({ success: true, msg: "Webhook processed" });

    } catch (error) {
        console.error("ProtonPay Payout Webhook Error:", error);
        return res.status(500).json({ success: false, error: error.message });
    }
};



module.exports = {
  dollarbazarWebhook,
  dollarbazarPayoutWebhook,
  protonpayWebhook,
  protonPayPayoutWebhook
};















// // controllers/webhook.controller.js
// const add_funds_module = require("../model/add_funds_module");
// const user_module = require("../model/user_module");
// const wallet_history = require("../model/wallet_trans_history_module"); // adjust path

// async function dollarbazarWebhook(req, res) {
//   try {
//     const payload = req.body || {};
//     console.log("DollarBazar Webhook Received:", payload);

//     // expected fields per docs:
//     // amount, transaction_status, transaction_datetime, transactionId, bankReference, orderId
//     const {
//       amount,
//       transaction_status,
//       transaction_datetime,
//       transactionId,
//       bankReference,
//       orderId,
//       // fallback names
//       merchant_reference
//     } = payload;

//     const merchantOrderId = orderId || merchant_reference;
//     if (!merchantOrderId) {
//       console.warn("Webhook missing orderId/merchant_reference");
//       return res.status(400).send("orderId missing");
//     }

//     const deposit = await add_funds_module.findOne({ tx_request_number: merchantOrderId });
//     if (!deposit) {
//       console.warn("Deposit not found for order:", merchantOrderId);
//       return res.status(200).send("no-entry"); // return 200 to avoid retries or change as per gateway expectations
//     }

//     // Avoid double-credit
//     if (deposit.fund_status === 1) {
//       console.log("Already processed:", merchantOrderId);
//       return res.status(200).send("already-processed");
//     }

//     if (transaction_status === "SUCCESS" || String(transaction_status).toUpperCase() === "SUCCESS") {
//       // credit wallet
//       const user = await user_module.findById(deposit.userDB_id);
//       if (!user) {
//         console.warn("User not found while processing webhook:", deposit.userDB_id);
//       } else {
//         user.wallet_balance = Number(user.wallet_balance || 0) + Number(amount || deposit.amount);
//         await user.save();

//         // mark deposit as success
//         deposit.fund_status = 1;
//         deposit.bank_utr = bankReference || deposit.bank_utr;
//         deposit.gateway_txn_id = transactionId || deposit.gateway_txn_id;
//         await deposit.save();

//         // create history
//         await wallet_history.create({
//           userDB_id: user._id,
//           amount: Number(amount || deposit.amount),
//           transaction_type: 1,
//           transaction_note: "UPI Auto Deposit - DollarBazar",
//           amount_status: 19,
//           txn_ref: transactionId || deposit.txn_ref,
//           tx_request_number: merchantOrderId
//         });
//       }
//     } else if (String(transaction_status).toUpperCase() === "FAIL") {
//       deposit.fund_status = 2; // failed
//       deposit.gateway_txn_id = transactionId || deposit.gateway_txn_id;
//       await deposit.save();
//     } else {
//       // e.g., INPROGRESS / PENDING
//       deposit.fund_status = deposit.fund_status || 0;
//       deposit.gateway_txn_id = transactionId || deposit.gateway_txn_id;
//       await deposit.save();
//     }

//     return res.status(200).send("OK");
//   } catch (err) {
//     console.error("webhook error:", err);
//     return res.status(500).send("ERR");
//   }
// }

// module.exports = {
//   dollarbazarWebhook
// };












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

// const dollarbazarWebhook = async (req, res) => {
//     try {
//         const data = req.body;
//         console.log("🚀 ~ dollarbazarWebhook ~ req.body:::::", req.body)

//         const {
//             amount,
//             transaction_status,
//             transactionid,
//             bankReference,
//             orderId
//         } = data;

//         const deposit = await add_funds_module.findOne({ tx_request_number: orderId });
//         if (!deposit) return res.send("Order not found");

//         if (deposit.fund_status === 1)
//             return res.send("Already credited");

//         if (transaction_status === "SUCCESS") {

//             const user = await user_module.findById(deposit.userDB_id);

//             user.wallet_balance += Number(amount);
//             await user.save();

//             deposit.fund_status = 1; // success
//             deposit.bank_utr = bankReference;
//             deposit.gateway_txn_id = transactionid;
//             await deposit.save();

//             await wallet_trans_history_module.create({
//                 userDB_id: user._id,
//                 amount: Number(amount),
//                 transaction_type: 1,
//                 transaction_note: "UPI Auto Deposit",
//                 amount_status: 19,
//                 txn_ref: transactionid,
//                 tx_request_number: orderId
//             });
//         }

//         if (transaction_status === "FAIL") {
//             deposit.fund_status = 2; // Failed
//             await deposit.save();
//         }

//         res.send("OK");

//     } catch (err) {
//         console.error("Webhook Error:", err);
//         res.status(200).send("ERROR");
//     }
// };

// module.exports = {
//     dollarbazarWebhook
// }
