import { Request, Response } from "express";
import { messages } from "../../../utills/common";
import { Transaction } from "../../../database/transaction/transaction";
import { sendErrorResponse, sendSuccessResponse } from "../../../utills/response";
import { Notification } from "../../../database/notification/notification";
export const depositByUser = async (req: Request, res: Response) => {
    try {
        const { depositAmount, userId,  } = req.body;
       
        let invest: any;
      
            // If the user hasn't invested before, create a new record
            invest =  await Transaction.create({
                userId,
                depositAmount,
                totalInvestedAmount: depositAmount
            }).save();
        await Notification.create({
            userId,
            msg: messages.notificationDepositMessage,
        }).save();

        return sendSuccessResponse(res, 200, messages.invest, invest);
    } catch (error) {
        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};

// get user transaction  by id
export const getUserTransactionById = async (req: Request, res: Response) => {
        try {
            const id = req.params.id;
            const { page = '1', limit = '10', type, search } = req.query;
            const pageNum = Math.max(1, parseInt(page as string, 10));
            const limitNum = Math.max(1, Math.min(100, parseInt(limit as string, 10)));
            const skip = (pageNum - 1) * limitNum;

            let query = Transaction.createQueryBuilder("transaction")
                .leftJoinAndSelect("transaction.userId", "userId")
                .orderBy("transaction.created_at", "DESC")
                .where({ userId: id });

            // Add type filter
            if (type === 'withdrawal') {
                query = query.andWhere("transaction.withdrawAmount > 0 AND transaction.iswithdrawAmount = true OR transaction.iswithdrawAmount = false AND transaction.isdepositAmount = false" );
            } else if (type === 'deposit') {
                query = query.andWhere("transaction.depositAmount > 0");
            } else if (type === 'transaction') {
                query = query.andWhere("(transaction.depositAmount > 0 OR transaction.withdrawAmount > 0)");
            }

            // Add search filter
            if (search) {
                query = query.andWhere(
                    `(CAST(transaction.depositAmount AS CHAR) LIKE :search
                    OR CAST(transaction.withdrawAmount AS CHAR) LIKE :search
                    OR CAST(transaction.totalInvestedAmount AS CHAR) LIKE :search
                    OR DATE_FORMAT(transaction.created_at, '%d %b %Y') LIKE :search)`,
                    { search: `%${search}%` }
                );
            }

            const [transactions, totalCount] = await query
                .skip(skip)
                .take(limitNum)
                .getManyAndCount();

            const totalPages = Math.ceil(totalCount / limitNum);

            return sendSuccessResponse(res, 200, messages.getUser, {
                transactions,
                pagination: {
                    currentPage: pageNum,
                    totalPages,
                    totalCount,
                    limit: limitNum
                }
            });
        } catch (error) {
            return sendErrorResponse(res, 500, messages.errorMsg);
        }
};

// invest amount add  after 3 days
export const updateAmounts = async () => {
        const allInvestments = await Transaction.createQueryBuilder("transaction")
            .orderBy("transaction.created_at", "ASC")
            .getMany();
        if (allInvestments.length > 0) {
            // const totalInvestedAmountSum = allInvestments.reduce((sum, investment) => sum + investment.totalInvestedAmount, 0);
            for (const investment of allInvestments) {
                const createdAt = new Date(investment.created_at);
                const threeDaysLater = new Date(createdAt);
                // threeDaysLater.setDate(createdAt.getDate() + 3);
                threeDaysLater.setMinutes(createdAt.getMinutes() + 1); 
                const currentTime = new Date().toISOString().split('.')[0];
                const threeDaysLaterTime = threeDaysLater.toISOString().split('.')[0]; 
                if (currentTime >= threeDaysLaterTime && !investment.isdepositAmount) {
                    await Transaction.update(
                        { created_at: createdAt.toISOString() },
                        {
                            // totalInvestedAmount: totalInvestedAmountSum,
                            isdepositAmount: true
                        }
                    );
                }
            }
        }
};


// for only testing
export const updateAmountsBymenual = async (req: Request, res: Response) => {
    try {
        const allInvestments = await Transaction.createQueryBuilder("transaction")
            .orderBy("transaction.created_at", "ASC")
            .getMany();
        if (allInvestments.length > 0) {
            const totalInvestedAmountSum = allInvestments.reduce((sum, investment) => sum + investment.totalInvestedAmount, 0);
            for (const investment of allInvestments) {
                const createdAt = new Date(investment.created_at);
                console.log("investment.iswithdrawAmount",investment.isdepositAmount);
                
                if (!investment.isdepositAmount) {
                    await Transaction.update(
                        { created_at: createdAt.toISOString() },
                        {
                            totalInvestedAmount: totalInvestedAmountSum,
                            isdepositAmount: true
                        }
                    );
                }
            }
        }
        return sendSuccessResponse(res, 200,'', "Investment amounts updated successfully.");
    } catch (error) {
        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};
