import { Request, Response } from "express";
import { messages } from "../../../utills/common";
import { sendErrorResponse, sendSuccessResponse } from "../../../utills/response";
import { Transaction } from "../../../database/transaction/transaction";
import { Notification } from "../../../database/notification/notification";
export const withdrawByUser = async (req: Request, res: Response) => {
    try {
        const { withdrawAmount, userId } = req.body;
         const allInvestments = await Transaction.createQueryBuilder()
        .where({userId})
        .getMany();
        const totalInvestedAmount = allInvestments.filter(transaction => transaction.isdepositAmount).reduce((sum, investment) => sum + investment.depositAmount, 0); 
        const totalwithdrawAmount = allInvestments.filter(transaction => transaction.iswithdrawAmount).reduce((sum, investment) => sum + investment.withdrawAmount, 0); 
        const remainingAmount = totalInvestedAmount - totalwithdrawAmount ;
        
        if (withdrawAmount > remainingAmount) {
            return sendErrorResponse(res, 400, messages.insufficientFunds);
        }
           const invest = await Transaction.create({
                withdrawAmount,
                userId,
                totalInvestedAmount: remainingAmount,
                created_at: new Date().toISOString(),
                updated_at: new Date().toISOString(),
            }).save();
        // Save the updated investment record
        await invest.save();
        await Notification.create({
            userId,
            amount: withdrawAmount,
            msg: messages.notificationWithdrawMessage,
        }).save();

        return sendSuccessResponse(res, 200, messages.withdrawSuccess, invest);
    } catch (error) {

        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};
