const asyncHandler = require('../middlewares/asyncHandler');
const {
  getAllDepartments,
  getDepartmentById,
  createDepartment,
  updateDepartment,
  deleteDepartment
} = require('../repositories/departmentsRepository');

// Get all departments
exports.getAllDepartments = asyncHandler(async (req, res) => {
    const rows = await getAllDepartments();
    res.status(200).json({ success: true, data: rows });
});

// Get department by ID
exports.getDepartmentById = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const department = await getDepartmentById(id);
    
    if (!department) {
        return res.status(404).json({ success: false, message: 'Department not found' });
    }
    
    res.status(200).json({ success: true, data: department });
});

// Create department (work area)
exports.createDepartment = asyncHandler(async (req, res) => {
    const { department_id, department_name } = req.body;
    
    if (!department_name) {
        return res.status(400).json({ success: false, message: 'department_name is required' });
    }
    
    const id = await createDepartment(department_name, department_id);
    res.status(201).json({ success: true, message: 'Department (work area) created successfully', data: { department_id: id } });
});

// Update department
exports.updateDepartment = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { department_name } = req.body;
    
    if (!department_name) {
        return res.status(400).json({ success: false, message: 'department_name is required' });
    }
    
    const updated = await updateDepartment(id, department_name);
    
    if (!updated) {
        return res.status(404).json({ success: false, message: 'Department not found' });
    }
    
    res.status(200).json({ success: true, message: 'Department updated successfully' });
});

// Delete department
exports.deleteDepartment = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const deleted = await deleteDepartment(id);
    
    if (!deleted) {
        return res.status(404).json({ success: false, message: 'Department not found' });
    }
    
    res.status(200).json({ success: true, message: 'Department deleted successfully' });
});

