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

export const getProfitdataWithGraph = async (req: Request, res: Response) => {
    try {
        const currentYear = new Date().getFullYear();
        const fiveYearsAgo = currentYear - 5;
        const userPortfolios = await UserPortfolio.createQueryBuilder("userPortfolio")
            .where("YEAR(userPortfolio.created_at) >= :fiveYearsAgo AND YEAR(userPortfolio.created_at) <= :currentYear",
                { fiveYearsAgo, currentYear })
            .orderBy("userPortfolio.created_at", "ASC")
            .getMany();
        
        const allTransactions = await Transaction.createQueryBuilder("transaction")
            .where({})
            .getMany();

        let pendingDepositAmount = 0;
        let totalInvestedAmountByUser = 0;
        let totalProfitByinvestedAmount = 0;

        allTransactions.forEach(user => {
            if (user.isdepositAmount) {
                totalInvestedAmountByUser += user?.depositAmount; // Assuming depositAmount is the field representing the deposit amount
            }
            if (!user.iswithdrawAmount) {
                pendingDepositAmount += user?.withdrawAmount; // Assuming depositAmount is the field representing the deposit amount
            }
            else{
                totalInvestedAmountByUser -= user?.withdrawAmount
            }
        });

        // Map to store aggregated profit data for each year
        const profitDataMap = new Map<number, number>();

        // Iterate through user portfolios to aggregate profit data
        userPortfolios.forEach(portfolio => {
            totalProfitByinvestedAmount += portfolio?.dailyProfitAmount;
            const year = new Date(portfolio.createdAt).getFullYear();
            if (profitDataMap.has(year)) {
                profitDataMap.set(year, profitDataMap.get(year)! + portfolio?.dailyProfitAmount);
            } else {
                profitDataMap.set(year, portfolio?.dailyProfitAmount);
            }
        }); 

        // Convert aggregated profit data map to array of objects in descending order of years
        const graphData = Array.from({ length: 6 }, (_, index) => {
            const year = currentYear - index;
            const totalProfit = profitDataMap.get(year) || 0;

            return { year, totalProfit: totalProfit.toFixed(2) }; // Formatting totalProfit to 2 decimal places
        }).reverse(); // Reversing the array to get descending order of years

        let investedAmount = 0;
        let dailyProfitPercentage = 0;
        let dailyProfitAmount = 0;

        if (userPortfolios.length > 0) {
            ({ investedAmount, dailyProfitPercentage, dailyProfitAmount } = userPortfolios[userPortfolios.length - 1]);
        }

        const quantCapitalProfit = (totalProfitByinvestedAmount * 20 / 100).toFixed(2); // Formatting quantCapitalProfit to 2 decimal places
        
        return sendSuccessResponse(res, 200, messages.viewData, {
            investedAmount: investedAmount.toFixed(2),
            profitLoss: dailyProfitPercentage.toFixed(2), 
            totalProfitAmount: dailyProfitAmount.toFixed(2), 
            pendingDepositAmount: pendingDepositAmount.toFixed(2), 
            quantCapitalProfit,
            totalInvestedAmountByUser: totalInvestedAmountByUser.toFixed(2),
            totalProfitByinvestedAmount: totalProfitByinvestedAmount.toFixed(2), 
            graphData
        });
    } catch (error) { 
        return sendErrorResponse(res, 500, messages.errorMsg);
    }
};
