const { Budget } = require('../models/budget');
const { Expense, ExpenseCategory } = require('../models/expense');
const { Op } = require('sequelize');
const { sequelize } = require('../config/db');

exports.setBudget = async (data, userId) => {
    // Check if budget exists for category+period
    let budget = await Budget.findOne({
        where: {
            expenseCategoryId: data.expenseCategoryId,
            period: data.period
        }
    });

    if (budget) {
        budget.amount = data.amount;
        await budget.save();
    } else {
        budget = await Budget.create({ ...data, createdBy: userId });
    }
    return budget;
};

exports.getBudgetStatus = async (period) => {
    // Get all budgets for period
    const budgets = await Budget.findAll({
        where: { period },
        include: [ExpenseCategory]
    });

    // Calculate actuals
    const status = [];
    for (const b of budgets) {
        // Assume period is YYYY-MM
        const startDate = `${period}-01`;
        // Calculate end date
        const parts = period.split('-');
        const year = parseInt(parts[0]);
        const month = parseInt(parts[1]);
        const lastDay = new Date(year, month, 0).getDate();
        const endDate = `${period}-${lastDay}`;

        const actual = await Expense.sum('amount', {
            where: {
                expenseCategoryId: b.expenseCategoryId,
                expenseDate: { [Op.between]: [startDate, endDate] }
            }
        }) || 0;

        status.push({
            budget: b,
            actual: Number(actual),
            percent: (Number(actual) / Number(b.amount)) * 100,
            remaining: Number(b.amount) - Number(actual)
        });
    }

    return status;
};

exports.deleteBudget = async (id) => {
    const budget = await Budget.findByPk(id);
    if (!budget) throw new Error('Budget not found');
    await budget.destroy();
    return true;
};
