import { Request, Response } from "express";
import { UserPortfolio } from "../../../database/transaction/usersPortfolio";
import { sendErrorResponse, sendSuccessResponse } from "../../../utills/response";
import { messages } from "../../../utills/common";
import { Transaction } from "../../../database/transaction/transaction";

export const getUserGraph = async (req: Request, res: Response) => {
    try {
        const userId = req.params.id;

        // Fetch user's transactions
        const transactions = await Transaction.createQueryBuilder("transaction")
            .orderBy("transaction.created_at", "ASC") // Order by ascending date
            .where("transaction.userId = :userId", { userId })
            .andWhere({})
            .getMany();

        // Initialize variables for day-by-day aggregation
        let cumulativeInvestedAmount = 0; 
        // Group transactions by day
        const transactionsByDate: { [key: string]: Transaction[] } = {};
        transactions.forEach(transaction => {
            const date = transaction.created_at.split("T")[0];  
            if (!transactionsByDate[date]) {
                transactionsByDate[date] = [];
            }
            transactionsByDate[date].push(transaction);
        });
        // Calculate daily profit percentage and day-end balance
        for (const date in transactionsByDate) {
            const dailyTransactions = transactionsByDate[date];
            let dayProfit = 0;
            dailyTransactions.forEach(transaction => {
                if (transaction.isdepositAmount) {
                    cumulativeInvestedAmount += transaction.depositAmount;
                } else {
                    dayProfit += transaction.depositAmount;
                }
            });
        }
        // Fetch user portfolio ordered by creation date (for total invested amount and profit calculations)
        const userPortfolios = await UserPortfolio.createQueryBuilder("userPortfolio")
            .orderBy("userPortfolio.created_at", "DESC")
            .getMany();

        const dailyProfitPercentage = userPortfolios[0]?.dailyProfitPercentage;
        const totalDepositAmount = transactions.filter(transaction => transaction.isdepositAmount).reduce((sum, transaction) => sum + transaction.depositAmount, 0);
        const totalWithdrawAmount = transactions.filter(transaction => transaction.iswithdrawAmount).reduce((sum, transaction) => sum + transaction.withdrawAmount, 0);
       
        const investedAmount = totalDepositAmount - totalWithdrawAmount;
         console.log(investedAmount,'totalWithdrawAmount')
        const userProfit = (investedAmount * dailyProfitPercentage) / 100;
        const userProfitOnInvestAmount = userProfit;
        const lastDailyProfitPercentage = ((userProfitOnInvestAmount) / investedAmount) * 100;

        const graphData: any[] = [];

        // Calculate dailyUserProfit and lastDailyProfitPercentage for each portfolio
        userPortfolios.forEach(portfolio => {
            // Find the most recent transaction that corresponds to the portfolio date (or earlier)
            let latestTransaction = transactions
                .filter(transaction => {
                    const transactionDate = new Date(transaction.created_at).toISOString().split("T")[0];  
                    const portfolioDateString = new Date(portfolio.createdAt).toISOString().split("T")[0];  
                    
                    
                    return transactionDate <= portfolioDateString; // Compare only the date part
                })
                .reduce<Transaction | null>((latest, transaction) => {
                    if (!latest || new Date(transaction.created_at) > new Date(latest.created_at)) {
                        return transaction;
                    }
                    return latest;
                }, null);

            if (!latestTransaction) return;

            const totalInvestedAmount = latestTransaction.totalInvestedAmount;
            const dailyProfitPercentage = portfolio.dailyProfitPercentage;
            const dailyUserProfit = (dailyProfitPercentage * totalInvestedAmount) / 100;
            const dayEndBalance = dailyUserProfit + totalInvestedAmount;

            graphData.push({
                dayEndBalance,
                dailyProfitPercentage,
                createdAt: portfolio.createdAt.toISOString()
            });
            // }
        });

        return sendSuccessResponse(res, 200, messages.viewData, {
            userProfitOnInvestAmount: investedAmount + userProfitOnInvestAmount,
            profitLosspercentage: lastDailyProfitPercentage,
            investedAmount: investedAmount,
            graphData
        });
    } catch (error) {
        console.log();

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