const Unit = require('../models/unit');

exports.getAllUnits = async (req, res) => {
    try {
        const units = await Unit.findAll();
        res.status(200).json({ data: units });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.createUnit = async (req, res) => {
    try {
        const { unit_name, unit_description } = req.body;
        const newUnit = await Unit.create({
            unit_name,
            unit_description,
        });
        res.status(201).json({ message: 'Unit created successfully', data: newUnit });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.updateUnit = async (req, res) => {
    try {
        const { id } = req.params;
        const { unit_name, unit_description } = req.body;
        const unit = await Unit.findByPk(id);
        if (unit) {
            unit.unit_name = unit_name || unit.unit_name;
            unit.unit_description = unit_description || unit.unit_description;
            await unit.save();
            res.status(200).json({ message: 'Unit updated successfully', data: unit });
        } else {
            res.status(404).json({ message: 'Unit not found' });
        }
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteUnit = async (req, res) => {
    try {
        const { id } = req.params;
        const unit = await Unit.findByPk(id);
        if (unit) {
            await unit.destroy();
            res.status(200).json({ message: 'Unit deleted successfully' });
        } else {
            res.status(404).json({ message: 'Unit not found' });
        }
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
