import Wallet from "../../DB/Model/payment/wallet.js";
import Stripe from "stripe";
import CustomError from "../../Utils/ResponseHandler/CustomError.js";
import CustomSuccess from "../../Utils/ResponseHandler/CustomSuccess.js";
import constants from "../../Utils/constants.js";
import envVars from "../../Config/env-vars.js";
import Payment from "../../DB/Model/payment/payments.model.js";
import Transactions from "../../DB/Model/payment/transactions.model.js";

const stripe = new Stripe(envVars.stripeSecretKey);

const connectWallet = async (req, res, next) => {
  try {
    const { user } = req;

    const fetchWallet = await Wallet.findOne({ user: user._id });

    if (fetchWallet) {
      return next(
        CustomSuccess.createSuccess(
          fetchWallet,
          "Wallet already connected.",
          200
        )
      );
    }

    const insertWallet = await Wallet.create({ user: user._id });

    return next(
      CustomSuccess.createSuccess(
        insertWallet,
        "Your wallet has been connected",
        200
      )
    );
  } catch (e) {
    console.log(e);
    return res.status(400).json(e);
  }
};

const fetchWallet = async (req, res, next) => {
  try {
    const { user } = req;
    let userWallet = await Wallet.findOne({ user: user._id });

    if (!userWallet) {
      return next(CustomError.badRequest("No Wallet Found!"));
    }

    return res.status(constants.OK).json({
      data: userWallet,
      message: "User Wallet has been Fetched",
      success: true,
    });
  } catch (e) {
    console.log(e);
    return res.status(400).json(e);
  }
};

const walletTopUp = async (req, res, next) => {
  try {
    const { user } = req;
    const amount = req.body.amount;

    let userWallet = await Wallet.findOne({ user: user._id });

    if (!userWallet) {
      return next(CustomError.badRequest("No Wallet Found!"));
    }

    // const updatedWallet = await Wallet.findByIdAndUpdate(
    //   userWallet._id,
    //   {
    //     $inc: { amount: amount },
    //   },
    //   { new: true }
    // );

    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount * 100,
      currency: "USD",
      customer: userWallet.customer_id,
    });

    const newPayment = await Payment.create({
      amount: amount,
      payment_intent_id: paymentIntent.id,
      created_by: user._id,
    });
    const newTransaction = await Transactions.create({
      status: "pending",
      send_by: user._id,
      payment_id: newPayment._id,
    });

    return res.status(constants.OK).json({
      data: { newTransaction, paymentIntent: paymentIntent.client_secret },
      message: "Top Up Successful",
      success: true,
    });
  } catch (e) {
    console.log(e);
    return res.status(400).json(e);
  }
};


const confirmTopUp = async (req, res, next) => {
  try {
    const { user } = req;
    const transactionId = req.body.transactionId

    const transactionDetails = await Transactions.findOne({ _id: transactionId }).populate("payment_id");


    if (!transactionDetails) {
      return res.status(404).json({
        success: false,
        message: "No pending transaction found",
      });
    }

    if (!transactionDetails.payment_id) {
      return res.status(400).json({
        success: false,
        message: "Payment details not found",
      });
    }

    const amount = transactionDetails.payment_id.amount;

    await Wallet.updateOne(
      { user: transactionDetails.send_by },
      { $inc: { amount: amount } }
    );

    await Transactions.updateOne(
      { _id: transactionDetails._id },
      { status: "completed" }
    );

    return res.status(200).json({
      success: true,
      message: "Top-up confirmed successfully",
    });

  } catch (e) {
    console.log(e);
    return res.status(400).json({ success: false, error: e.message });
  }
};

const WalletControllers = {
  connectWallet,
  fetchWallet,
  walletTopUp,
  confirmTopUp
};
export default WalletControllers;
