import dbConnect from "@/database/dbConnect";
import { NextResponse } from "next/server";
import incomeModel from "@/database/models/incomeModel";
import expenseModel from "@/database/models/expenseModel";

// GET METHOD - Fetch monthly and yearly income/expense analytics
export async function GET(req: Request) {
    try {
        await dbConnect();
        
        const url = new URL(req.url);
        const view = url.searchParams.get('view') || 'monthly'; // 'monthly' or 'yearly'
        const year = parseInt(url.searchParams.get('year') || new Date().getFullYear().toString());
        const month = parseInt(url.searchParams.get('month') || (new Date().getMonth() + 1).toString());
        
        let data = {};
        
        if (view === 'monthly') {
            // Get monthly data for the specified year
            const monthlyData = [];
            
            for (let m = 1; m <= 12; m++) {
                const startOfMonth = new Date(year, m - 1, 1);
                const endOfMonth = new Date(year, m, 0, 23, 59, 59, 999);
                
                const startUnix = Math.floor(startOfMonth.getTime() / 1000);
                const endUnix = Math.floor(endOfMonth.getTime() / 1000);
                
                // Aggregate income for this month
                const incomeResult = await incomeModel.aggregate([
                    {
                        $match: {
                            addedAt: { $gte: startUnix, $lte: endUnix }
                        }
                    },
                    {
                        $group: {
                            _id: null,
                            totalIncome: { $sum: "$amount" },
                            count: { $sum: 1 }
                        }
                    }
                ]);
                
                // Aggregate expenses for this month
                const expenseResult = await expenseModel.aggregate([
                    {
                        $match: {
                            addedAt: { $gte: startUnix, $lte: endUnix }
                        }
                    },
                    {
                        $group: {
                            _id: null,
                            totalExpense: { $sum: "$amount" },
                            count: { $sum: 1 }
                        }
                    }
                ]);
                
                monthlyData.push({
                    month: m,
                    monthName: new Date(year, m - 1).toLocaleString('default', { month: 'long' }),
                    income: incomeResult[0]?.totalIncome || 0,
                    expense: expenseResult[0]?.totalExpense || 0,
                    incomeCount: incomeResult[0]?.count || 0,
                    expenseCount: expenseResult[0]?.count || 0,
                    net: (incomeResult[0]?.totalIncome || 0) - (expenseResult[0]?.totalExpense || 0)
                });
            }
            
            data = {
                view: 'monthly',
                year,
                months: monthlyData,
                totalIncome: monthlyData.reduce((sum, month) => sum + month.income, 0),
                totalExpense: monthlyData.reduce((sum, month) => sum + month.expense, 0),
                totalNet: monthlyData.reduce((sum, month) => sum + month.net, 0)
            };
            
        } else if (view === 'yearly') {
            // Get yearly data for the last 5 years
            const currentYear = new Date().getFullYear();
            const yearlyData = [];
            
            for (let y = currentYear - 4; y <= currentYear; y++) {
                const startOfYear = new Date(y, 0, 1);
                const endOfYear = new Date(y, 11, 31, 23, 59, 59, 999);
                
                const startUnix = Math.floor(startOfYear.getTime() / 1000);
                const endUnix = Math.floor(endOfYear.getTime() / 1000);
                
                // Aggregate income for this year
                const incomeResult = await incomeModel.aggregate([
                    {
                        $match: {
                            addedAt: { $gte: startUnix, $lte: endUnix }
                        }
                    },
                    {
                        $group: {
                            _id: null,
                            totalIncome: { $sum: "$amount" },
                            count: { $sum: 1 }
                        }
                    }
                ]);
                
                // Aggregate expenses for this year
                const expenseResult = await expenseModel.aggregate([
                    {
                        $match: {
                            addedAt: { $gte: startUnix, $lte: endUnix }
                        }
                    },
                    {
                        $group: {
                            _id: null,
                            totalExpense: { $sum: "$amount" },
                            count: { $sum: 1 }
                        }
                    }
                ]);
                
                yearlyData.push({
                    year: y,
                    income: incomeResult[0]?.totalIncome || 0,
                    expense: expenseResult[0]?.totalExpense || 0,
                    incomeCount: incomeResult[0]?.count || 0,
                    expenseCount: expenseResult[0]?.count || 0,
                    net: (incomeResult[0]?.totalIncome || 0) - (expenseResult[0]?.totalExpense || 0)
                });
            }
            
            data = {
                view: 'yearly',
                years: yearlyData,
                totalIncome: yearlyData.reduce((sum, year) => sum + year.income, 0),
                totalExpense: yearlyData.reduce((sum, year) => sum + year.expense, 0),
                totalNet: yearlyData.reduce((sum, year) => sum + year.net, 0)
            };
        }
        
        return NextResponse.json({
            success: true,
            message: "Analytics data retrieved successfully",
            data
        }, {
            status: 200,
            headers: {
                "content-type": "application/json"
            }
        });
        
    } catch (error) {
        console.error("Error fetching income/expense analytics:", error);
        return NextResponse.json({
            success: false,
            message: "Server error"
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        });
    }
}