const incomeService = require('../services/incomeService');

exports.createIncome = async (req, res) => {
    try {
        const income = await incomeService.createIncome(req.body, req.user.id);
        res.status(201).json(income);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getIncomes = async (req, res) => {
    try {
        const incomes = await incomeService.getAllIncomes(req.query);
        res.json(incomes);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getIncome = async (req, res) => {
    try {
        const income = await incomeService.getIncomeById(req.params.id);
        if (!income) return res.status(404).json({ message: 'Not found' });
        res.json(income);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.updateIncome = async (req, res) => {
    try {
        const income = await incomeService.updateIncome(req.params.id, req.body, req.user.id);
        res.json(income);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteIncome = async (req, res) => {
    try {
        await incomeService.deleteIncome(req.params.id, req.user.id);
        res.status(204).send();
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getSummary = async (req, res) => {
    try {
        const summary = await incomeService.getIncomeSummary();
        res.json(summary);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getCategories = async (req, res) => {
    try {
        const cats = await incomeService.getCategories();
        res.json(cats);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.createCategory = async (req, res) => {
    try {
        const cat = await incomeService.createCategory(req.body);
        res.status(201).json(cat);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.updateCategory = async (req, res) => {
    try {
        const cat = await incomeService.updateCategory(req.params.id, req.body);
        res.json(cat);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteCategory = async (req, res) => {
    try {
        await incomeService.deleteCategory(req.params.id);
        res.json({ message: 'Category deleted' });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};
