const Categories = require('../models/CategoryModel');

exports.getCategories = async (req, res) => {
    try {
        const response = await Categories.findAll({
            where: { user_id: req.userId }
        });
        res.json(response);
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Error mengambil data kategori"});
    }
}

exports.createCategory = async (req, res) => {
    const { name, type, budget_limit } = req.body;
    try {
        await Categories.create({
            name, type,
            budget_limit: budget_limit || 0,
            user_id: req.userId
        });
        res.json({msg: "Kategori Berhasil Dibuat!"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal membuat kategori"});
    }
}

exports.updateCategory = async (req, res) => {
    try {
        const category = await Categories.findOne({
            where: { id: req.params.id, user_id: req.userId }
        });
        if(!category) return res.status(404).json({msg: "Kategori tidak ditemukan"});

        const { name, type, budget_limit } = req.body;
        await category.update({ name, type, budget_limit });
        res.json({msg: "Kategori Berhasil Diupdate"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal update kategori"});
    }
}

exports.deleteCategory = async (req, res) => {
    try {
        const category = await Categories.findOne({
            where: { id: req.params.id, user_id: req.userId }
        });
        if(!category) return res.status(404).json({msg: "Kategori tidak ditemukan"});

        await category.destroy();
        res.json({msg: "Kategori Berhasil Dihapus"});
    } catch (error) {
        console.log(error);
        res.status(500).json({msg: "Gagal hapus kategori"});
    }
}