import dbConnect from "@/database/dbConnect";
import { NextResponse } from "next/server";
import userModel from "@/database/models/userModel";
import memberModel from "@/database/models/memberModel";
import servicesModel from "@/database/models/serviceModel";
import statisticsModel from "@/database/models/statisticsModel";
import workerModel from "@/database/models/workerModel";
import { Types } from 'mongoose'
import { IStatisticsSchema } from '@/types/IDB'

// set the revalidate variable
export const revalidate = 5;

/**
 * Updates the members general overview statistics for the current week, month, and year in the database.
 * This function calculates total members, active/unactive subscriptions, and gender-based counts
 * for each day of the current week, aggregates them into weeks for the current month,
 * and then into months for the current year, storing it in the statisticsModel.
 */
async function updateMembersOverviewStatistics() {
    try {
        await dbConnect(); // Ensure DB connection

        // Define week days in order, starting from Saturday as per frontend
        const weekDaysOrder = ['sat', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri'];

        const now = new Date();
        // Set to the start of today (local time)
        now.setHours(0, 0, 0, 0);

        const currentUnix = Math.floor(new Date().getTime() / 1000);

        // --- Calculate thisWeek data ---
        let currentDayOfWeek = now.getDay(); // 0 (Sunday) to 6 (Saturday)
        let daysToSubtract;
        if (currentDayOfWeek === 6) { // If today is Saturday
            daysToSubtract = 0;
        } else { // For any other day, calculate how many days back to last Saturday
            daysToSubtract = (currentDayOfWeek + 1);
        }

        const startOfWeek = new Date(now);
        startOfWeek.setDate(now.getDate() - daysToSubtract);
        startOfWeek.setHours(0, 0, 0, 0); // Ensure it's the very start of Saturday

        let thisWeekDaysData: { [key: string]: { [key: string]: number } } = {};

        for (let i = 0; i < 7; i++) {
            const day = new Date(startOfWeek);
            day.setDate(startOfWeek.getDate() + i);

            const endOfDay = new Date(day);
            endOfDay.setDate(day.getDate() + 1); // Move to the next day
            const endOfDayUnix = Math.floor(endOfDay.getTime() / 1000);

            // Calculate cumulative totals up to this day (inclusive)
            const totalMembers = await memberModel.countDocuments({
                registerAt_unix: { $lt: endOfDayUnix }
            });

            // Count members with at least one active service subscription
        const totalActiveSubs = await memberModel.countDocuments({
            registerAt_unix: { $lt: endOfDayUnix },
            'services': {
                $elemMatch: {
                    'planExpAt_unix': { $gt: currentUnix },
                    'active': true
                }
            }
        });

        // Count members with no active service subscriptions
        const totalUnActiveSubs = await memberModel.countDocuments({
            registerAt_unix: { $lt: endOfDayUnix },
            $or: [
                { 'services': { $size: 0 } },
                {
                    'services': {
                        $not: {
                            $elemMatch: {
                                'planExpAt_unix': { $gt: currentUnix },
                                'active': true
                            }
                        }
                    }
                }
            ]
        });

            const totalMansMembers = await memberModel.countDocuments({
                gendre: 'm',
                registerAt_unix: { $lt: endOfDayUnix }
            });

            const totalGirlsMembers = await memberModel.countDocuments({
                gendre: 'w',
                registerAt_unix: { $lt: endOfDayUnix }
            });

            thisWeekDaysData[weekDaysOrder[i]] = {
                totalMembers,
                totalActiveSubs,
                totalUnActiveSubs,
                totalMansMembers,
                totalGirlsMembers,
            };
        }

        const thisWeekData = {
            year: startOfWeek.getFullYear(),
            month: startOfWeek.getMonth(), // 0-indexed month
            week: Math.ceil(startOfWeek.getDate() / 7), // Simplified week number
            days: thisWeekDaysData
        };

        // --- Calculate thisMonth data ---
        const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
        startOfMonth.setHours(0, 0, 0, 0);

        let thisMonthWeeksData = [];
        let tempDate = new Date(startOfMonth);
        let weekCounter = 1;

        while (tempDate.getMonth() === now.getMonth()) {
            const startOfWeekInMonth = new Date(tempDate);
            startOfWeekInMonth.setDate(tempDate.getDate() - ((tempDate.getDay() + 1) % 7)); // Back to last Saturday
            startOfWeekInMonth.setHours(0, 0, 0, 0);

            if (startOfWeekInMonth.getMonth() !== now.getMonth() && startOfWeekInMonth.getTime() < startOfMonth.getTime()) {
                startOfWeekInMonth.setTime(startOfMonth.getTime());
            }

            let weekSum = {
                totalMembers: 0,
                totalActiveSubs: 0,
                totalUnActiveSubs: 0,
                totalMansMembers: 0,
                totalGirlsMembers: 0
            };
            let daysInWeek = {};
            let lastDayOfWeek = null;

            for (let i = 0; i < 7; i++) {
                const dayInWeek = new Date(startOfWeekInMonth);
                dayInWeek.setDate(startOfWeekInMonth.getDate() + i);

                // Only consider days within the current month
                if (dayInWeek.getMonth() === now.getMonth()) {
                    const endOfDay = new Date(dayInWeek);
                    endOfDay.setDate(dayInWeek.getDate() + 1);
                    const endOfDayUnix = Math.floor(endOfDay.getTime() / 1000);

                    // Calculate cumulative totals up to this day (inclusive)
                    const totalMembers = await memberModel.countDocuments({
                        registerAt_unix: { $lt: endOfDayUnix }
                    });
                    // Count members with at least one active service subscription
                    const totalActiveSubs = await memberModel.countDocuments({
                        registerAt_unix: { $lt: endOfDayUnix },
                        'services': {
                            $elemMatch: {
                                'planExpAt_unix': { $gt: currentUnix },
                                'active': true
                            }
                        }
                    });
                    
                    // Count members with no active service subscriptions
                    const totalUnActiveSubs = await memberModel.countDocuments({
                        registerAt_unix: { $lt: endOfDayUnix },
                        $or: [
                            { 'services': { $size: 0 } },
                            {
                                'services': {
                                    $not: {
                                        $elemMatch: {
                                            'planExpAt_unix': { $gt: currentUnix },
                                            'active': true
                                        }
                                    }
                                }
                            }
                        ]
                    });
                    const totalMansMembers = await memberModel.countDocuments({
                        gendre: 'm',
                        registerAt_unix: { $lt: endOfDayUnix }
                    });
                    const totalGirlsMembers = await memberModel.countDocuments({
                        gendre: 'w',
                        registerAt_unix: { $lt: endOfDayUnix }
                    });

                    (daysInWeek as {[key: string]: any})[weekDaysOrder[i]] = {
                        totalMembers,
                        totalActiveSubs,
                        totalUnActiveSubs,
                        totalMansMembers,
                        totalGirlsMembers,
                    };

                    // Keep track of the last day's totals for the week sum
                    lastDayOfWeek = {
                        totalMembers,
                        totalActiveSubs,
                        totalUnActiveSubs,
                        totalMansMembers,
                        totalGirlsMembers,
                    };
                }
            }

            // Set week sum to the cumulative total at the end of the week
            if (lastDayOfWeek) {
                weekSum = lastDayOfWeek;
            }

            thisMonthWeeksData.push({
                week: weekCounter,
                days: daysInWeek,
                thisWeekSum: weekSum // This matches the frontend's expected structure for thisMonthTotalSum
            });

            tempDate.setDate(tempDate.getDate() + 7); // Move to the next week
            weekCounter++;
        }

        const thisMonthData = {
            year: now.getFullYear(),
            month: now.getMonth(),
            weeks: thisMonthWeeksData
        };

        // --- Calculate thisYear data ---
        let thisYearMonthsDataForFrontendAndDB = []; // This will contain months with full weeks data and total sum

        for (let month = 0; month < 12; month++) {
            const startOfMonthOfYear = new Date(now.getFullYear(), month, 1);
            startOfMonthOfYear.setHours(0, 0, 0, 0);

            let monthlyWeeksData = []; // Weeks data for this specific month
            let tempMonthDateForYear = new Date(startOfMonthOfYear);
            let monthWeekCounterForYear = 1;

            let totalMonthSum = { // Sum for the entire month for the year view
                totalMembers: 0, totalActiveSubs: 0, totalUnActiveSubs: 0,
                totalMansMembers: 0, totalGirlsMembers: 0
            };

            while (tempMonthDateForYear.getMonth() === month) {
                const startOfWeekInMonthForYear = new Date(tempMonthDateForYear);
                startOfWeekInMonthForYear.setDate(tempMonthDateForYear.getDate() - ((tempMonthDateForYear.getDay() + 1) % 7));
                startOfWeekInMonthForYear.setHours(0, 0, 0, 0);

                if (startOfWeekInMonthForYear.getMonth() !== month && startOfWeekInMonthForYear.getTime() < startOfMonthOfYear.getTime()) {
                    startOfWeekInMonthForYear.setTime(startOfMonthOfYear.getTime());
                }

                let daysInMonthlyWeekForYear = {};
                let currentWeeklySumForYear = { // Sum for the current week within the month
                    totalMembers: 0, totalActiveSubs: 0, totalUnActiveSubs: 0,
                    totalMansMembers: 0, totalGirlsMembers: 0
                };

                for (let i = 0; i < 7; i++) {
                    const dayInMonthlyWeekForYear = new Date(startOfWeekInMonthForYear);
                    dayInMonthlyWeekForYear.setDate(startOfWeekInMonthForYear.getDate() + i);

                    if (dayInMonthlyWeekForYear.getMonth() === month) {
                        const endOfDay = new Date(dayInMonthlyWeekForYear);
                        endOfDay.setDate(dayInMonthlyWeekForYear.getDate() + 1);
                        const endOfDayUnix = Math.floor(endOfDay.getTime() / 1000);

                        // Calculate cumulative totals up to this day (inclusive)
                        const totalMembers = await memberModel.countDocuments({
                            registerAt_unix: { $lt: endOfDayUnix }
                        });
                        // Count members with at least one active service subscription
                        const totalActiveSubs = await memberModel.countDocuments({
                            registerAt_unix: { $lt: endOfDayUnix },
                            'services': {
                                $elemMatch: {
                                    'planExpAt_unix': { $gt: currentUnix },
                                    'active': true
                                }
                            }
                        });
                        
                        // Count members with no active service subscriptions
                        const totalUnActiveSubs = await memberModel.countDocuments({
                            registerAt_unix: { $lt: endOfDayUnix },
                            $or: [
                                { 'services': { $size: 0 } },
                                {
                                    'services': {
                                        $not: {
                                            $elemMatch: {
                                                'planExpAt_unix': { $gt: currentUnix },
                                                'active': true
                                            }
                                        }
                                    }
                                }
                            ]
                        });
                        const totalMansMembers = await memberModel.countDocuments({
                            gendre: 'm',
                            registerAt_unix: { $lt: endOfDayUnix }
                        });
                        const totalGirlsMembers = await memberModel.countDocuments({
                            gendre: 'w',
                            registerAt_unix: { $lt: endOfDayUnix }
                        });

                        (daysInMonthlyWeekForYear as {[key: string]: any})[weekDaysOrder[i]] = {
                            totalMembers,
                            totalActiveSubs,
                            totalUnActiveSubs,
                            totalMansMembers,
                            totalGirlsMembers,
                        };

                        // Keep the last day's totals as the week sum (cumulative total at end of week)
                        currentWeeklySumForYear = {
                            totalMembers,
                            totalActiveSubs,
                            totalUnActiveSubs,
                            totalMansMembers,
                            totalGirlsMembers,
                        };
                    }
                }

                monthlyWeeksData.push({
                    week: monthWeekCounterForYear,
                    days: daysInMonthlyWeekForYear,
                    thisWeekSum: currentWeeklySumForYear // Sum for this specific week
                });

                // Keep the last week's totals as the month sum (cumulative total at end of month)
                totalMonthSum = {
                    totalMembers: currentWeeklySumForYear.totalMembers,
                    totalActiveSubs: currentWeeklySumForYear.totalActiveSubs,
                    totalUnActiveSubs: currentWeeklySumForYear.totalUnActiveSubs,
                    totalMansMembers: currentWeeklySumForYear.totalMansMembers,
                    totalGirlsMembers: currentWeeklySumForYear.totalGirlsMembers,
                };

                tempMonthDateForYear.setDate(tempMonthDateForYear.getDate() + 7);
                monthWeekCounterForYear++;
            }
            
            thisYearMonthsDataForFrontendAndDB.push({
                month: month,
                weeks: monthlyWeeksData, // This is crucial for frontend's thisYear.months[x].weeks
                thisMonthWeeksSum: totalMonthSum // The rolled-up sum for the month
            });
        }

        const thisYearData = {
            year: now.getFullYear(),
            months: thisYearMonthsDataForFrontendAndDB // Both frontend and DB will use this detailed structure
        };

        // --- Update the statistics document ---
        let statistics = await statisticsModel.findOne({});

        if (!statistics) {
            statistics = new statisticsModel({
                listsTracking: {
                    thisWeek: thisWeekData,
                    thisMonth: thisMonthData,
                    thisYear: thisYearData, // Use the detailed data for thisYear
                    months: [thisMonthData], // Store current month's full data in array
                    years: [thisYearData]   // Store current year's full detailed data in array
                }
            });
            await statistics.save();
        } else {
            // Update thisWeek, thisMonth, thisYear directly (for current period display)
            statistics.listsTracking.thisWeek = thisWeekData;
            statistics.listsTracking.thisMonth = thisMonthData;
            statistics.listsTracking.thisYear = thisYearData; // Update with the detailed data

            // Update or add current month in listsTracking.months array (for historical list)
            const currentMonthIndex = statistics.listsTracking.months.findIndex(m => m.year === thisMonthData.year && m.month === thisMonthData.month);
            if (currentMonthIndex !== -1) {
                statistics.listsTracking.months[currentMonthIndex] = thisMonthData;
            } else {
                // To avoid too many empty entries if listsTracking.months is for *all* months in current year
                // and not just a historical log. If it's a fixed size array (12 months),
                // we can update by index. If it's a dynamic historical log, push is fine.
                // Assuming it's for current year's months, better to update by index or push if month is not there.
                // For simplicity and matching current structure, push if not found.
                statistics.listsTracking.months.push(thisMonthData);
            }
            
            // Update or add current year in listsTracking.years array (for historical list)
            const currentYearIndex = statistics.listsTracking.years.findIndex(y => y.year === thisYearData.year);
            if (currentYearIndex !== -1) {
                statistics.listsTracking.years[currentYearIndex] = thisYearData; // Update with full detailed data
            } else {
                statistics.listsTracking.years.push(thisYearData); // Push full detailed data
            }

            await statistics.save();
        }

        console.log("Members overview statistics updated successfully for this week, month, and year.");

    } catch (error) {
        console.error("Error updating members overview statistics:", error);
    }
}

// GET METHOD
export async function GET(req:Request)
{
    try{
        await updateMembersOverviewStatistics(); // Call the updater function first
        // connect to the db
        dbConnect();
        // get needed docs
        let membersCount : number = await memberModel.count({})
        let activeMembersCount : number = await memberModel.count({active: true})
        let disActiveMembersCount : number = await memberModel.count({active: false})
        // Count members with at least one active service subscription
        let activeSubscriptionsCount : number = await memberModel.count({
            'services': {
                $elemMatch: {
                    'planExpAt_unix': { $gt: Math.floor(new Date().getTime() / 1000) },
                    'active': true
                }
            }
        });
        
        // Count members with subscriptions expiring soon (within 3 days)
        let expiredSoonSubscriptionsCount : number = await memberModel.count({
            'services': {
                $elemMatch: {
                    'planExpAt_unix': { 
                        $gt: Math.floor(new Date().getTime() / 1000),
                        $lte: Math.floor(new Date().getTime() / 1000) + 259200
                    },
                    'active': true
                }
            }
        });
        
        // Count members with no active service subscriptions
        let expiredSubscriptionsCount : number = await memberModel.count({
            $or: [
                { 'services': { $size: 0 } },
                {
                    'services': {
                        $not: {
                            $elemMatch: {
                                'planExpAt_unix': { $gt: Math.floor(new Date().getTime() / 1000) },
                                'active': true
                            }
                        }
                    }
                }
            ]
        }); 
        let servicesCount : number = await servicesModel.count({})
        let activeServicesCount : number = await servicesModel.count({status: "active"})
        let disActiveServicesCount : number = await servicesModel.count({status: "inactive"})
        let servicesNameAndSubscribers :
            {
                _id: Types.ObjectId,
                name: string,
                totalSubscribers: number
            }[]
        = await servicesModel.find({} , {name: 1 , totalSubscribers : 1})
        let workersNameAndJobType : { count: number , jobType: string }[] = await workerModel.aggregate([
            {
                $group: {
                    _id: "$jobType",
                    count: { $sum: 1 }
                }
            },
            {
                $project: {
                    jobType: "$_id",
                    count: 1,
                    _id: 0
                }
            }
        ])
        let membersGendre : { count: number , gendre: string }[] = await memberModel.aggregate([
            {
                $group: {
                    _id: "$gendre",
                    count: { $sum: 1 }
                }
            },
            {
                $project: {
                    gendre: "$_id",
                    count: 1,
                    _id: 0
                }
            }
        ])
        // get members general overview
        let membersGeneralOverview : {
            thisWeek : {
                'year': number,
                'month': number,
                'week': number,
                'days': {
                    'sat': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'sun': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'mon': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'tue': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'wed': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'thu': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    },
                    'fri': {
                        'totalMembers': number,
                        'totalActiveSubs': number,
                        'totalUnActiveSubs': number,
                        'totalMansMembers': number,
                        'totalGirlsMembers': number,
                    }
                }
            },
            months : {
                'year': number,
                'month': number,
                'weeks': {
                    'week': number,
                    'days': {
                        'sat': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'sun': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'mon': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'tue': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'wed': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'thu': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'fri': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        }
                    }[]
                }[]
            }[],
            years : {
                'year': number,
                'months': {
                    'month': number,
                    'weeks': {
                        'week': number,
                        'days': {
                            'sat': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'sun': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'mon': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'tue': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'wed': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'thu': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'fri': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            }
                        }[]
                    }[]
                }[]
            }[],
            thisMonth: {
                'year': number,
                'month': number,
                'weeks': {
                    'week': number,
                    'days': {
                        'sat': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'sun': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'mon': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'tue': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'wed': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'thu': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        },
                        'fri': {
                            'totalMembers': number,
                            'totalActiveSubs': number,
                            'totalUnActiveSubs': number,
                            'totalMansMembers': number,
                            'totalGirlsMembers': number,
                        }
                    }[]
                }[]
            },
            thisYear: {
                'year': number,
                'months': {
                    'month': number,
                    'weeks': {
                        'week': number,
                        'days': {
                            'sat': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'sun': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'mon': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'tue': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'wed': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'thu': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            },
                            'fri': {
                                'totalMembers': number,
                                'totalActiveSubs': number,
                                'totalUnActiveSubs': number,
                                'totalMansMembers': number,
                                'totalGirlsMembers': number,
                            }
                        }[]
                    }[]
                }[]
            }
        } =
        {
            thisWeek : {
                'year': 0,
                'month': 0,
                'week': 0,
                'days': {
                    'sat': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'sun': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'mon': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'tue': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'wed': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'thu': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    },
                    'fri': {
                        'totalMembers': 0,
                        'totalActiveSubs': 0,
                        'totalUnActiveSubs': 0,
                        'totalMansMembers': 0,
                        'totalGirlsMembers': 0,
                    }
                }
            },
            months : [{
                'year': 0,
                'month': 0,
                'weeks': [{
                    'week': 0,
                    'days': [{
                        'sat': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'sun': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'mon': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'tue': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'wed': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'thu': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        },
                        'fri': {
                            'totalMembers': 0,
                            'totalActiveSubs': 0,
                            'totalUnActiveSubs': 0,
                            'totalMansMembers': 0,
                            'totalGirlsMembers': 0,
                        }
                    }]
                }]
            }],
            years : [{
                'year': 0,
                'months': [{
                    'month': 0,
                    'weeks': [{
                        'week': 0,
                        'days': {
                            'sat': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'sun': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'mon': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'tue': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'wed': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'thu': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            },
                            'fri': {
                                'totalMembers': 0,
                                'totalActiveSubs': 0,
                                'totalUnActiveSubs': 0,
                                'totalMansMembers': 0,
                                'totalGirlsMembers': 0,
                            }
                        }
                    }]
                }]
            }]
        };
        let statistics = await statisticsModel.findOne({});
        if(statistics?.listsTracking)
        {
            membersGeneralOverview.thisWeek = statistics?.listsTracking.thisWeek
            membersGeneralOverview.thisMonth = statistics?.listsTracking.months.filter((month) => month.month == (new Date()).getMonth())[0]
            membersGeneralOverview.thisYear = statistics?.listsTracking.years.filter((year) => year.year == (new Date()).getFullYear())[0]
        }
        // prepare the report
        let report = {
            membersCount: {
                name: "membersCount",
                value: membersCount,
            },
            activeSubscriptionsCount: {
                name: "activeSubscriptionsCount",
                value: activeSubscriptionsCount,
            },
            expiredSoonSubscriptionsCount: {
                name: "expiredSoonSubscriptionsCount",
                value: expiredSoonSubscriptionsCount,
            },
            expiredSubscriptionsCount: {
                name: "expiredSubscriptionsCount",
                value: expiredSubscriptionsCount,
            },
            activeMembersCount: {
                name: "activeMembersCount",
                value: activeMembersCount,
            },
            disActiveMembersCount: {
                name: "disActiveMembersCount",
                value: disActiveMembersCount,
            },
            servicesCount: {
                name: "servicesCount",
                value: servicesCount,
            },
            activeServicesCount: {
                name: "activeServicesCount",
                value: activeServicesCount,
            },
            disActiveServicesCount: {
                name: "disActiveServicesCount",
                value: disActiveServicesCount,
            },
            membersGeneralOverview: {
                name: "membersGeneralOverview",
                value: membersGeneralOverview,
            },
            servicesNameAndSubscribers: {
                name: "servicesNameAndSubscribers",
                value: servicesNameAndSubscribers,
            },
            workersNameAndJobType: {
                name: "workersNameAndJobType",
                value: workersNameAndJobType,
            },
            membersGendre: {
                name: "membersGendre",
                value: membersGendre,
            },
            totalIncome: statistics?.totalIncome,
            totalOutcome: statistics?.totalOutcome
        }        
        // return the success response
        return NextResponse.json({
            success: true,
            message: "requestTerminatedWithSuccess",
            data: report,
        }, {
            status: 200,
            headers: {
                "content-type": "application/json"
            }
        })
    }catch(e)
    {
        console.log(e)
        // catch any error and return an error response
        return NextResponse.json({
            success: false,
            message: "serverError",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        })
    }
}