const { pool } = require('../config/db');

const createDepartment = async (req, res) => {
    const { deptCode, deptName, salaryID } = req.body;
    
    if (!deptCode || !deptName || !salaryID) {
        return res.status(400).json({ message: 'Department code, name and salaryID are required' });
    }
    
    try {
        const [result] = await pool.execute(
            'INSERT INTO department (deptCode, deptName, salaryID) VALUES (?, ?, ?)',
            [deptCode, deptName, salaryID]
        );
        
        res.status(201).json({ 
            message: 'Department created successfully',
            deptCode: deptCode
        });
    } catch (error) {
        console.error('Create department error:', error);
        res.status(500).json({ message: 'Failed to create department', error: error.message });
    }
};

const getAllDepartments = async (req, res) => {
    try {
        const [departments] = await pool.execute(`
            SELECT d.*, s.grossSalary, s.totalDeduction, s.netSalary, s.month
            FROM department d
            LEFT JOIN salary s ON d.salaryID = s.salaryID
        `);
        
        res.json(departments);
    } catch (error) {
        console.error('Get departments error:', error);
        res.status(500).json({ message: 'Failed to fetch departments', error: error.message });
    }
};

const getDepartmentByCode = async (req, res) => {
    const { code } = req.params;
    
    try {
        const [departments] = await pool.execute(`
            SELECT d.*, s.grossSalary, s.totalDeduction, s.netSalary, s.month
            FROM department d
            LEFT JOIN salary s ON d.salaryID = s.salaryID
            WHERE d.deptCode = ?
        `, [code]);
        
        if (departments.length === 0) {
            return res.status(404).json({ message: 'Department not found' });
        }
        
        res.json(departments[0]);
    } catch (error) {
        console.error('Get department error:', error);
        res.status(500).json({ message: 'Failed to fetch department', error: error.message });
    }
};

const updateDepartment = async (req, res) => {
    const { code } = req.params;
    const { deptName, salaryID } = req.body;
    
    try {
        const [result] = await pool.execute(
            'UPDATE department SET deptName = ?, salaryID = ? WHERE deptCode = ?',
            [deptName, salaryID, code]
        );
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Department not found' });
        }
        
        res.json({ message: 'Department updated successfully' });
    } catch (error) {
        console.error('Update department error:', error);
        res.status(500).json({ message: 'Failed to update department', error: error.message });
    }
};

const deleteDepartment = async (req, res) => {
    const { code } = req.params;
    
    try {
        const [employees] = await pool.execute('SELECT * FROM employee WHERE deptCode = ?', [code]);
        if (employees.length > 0) {
            return res.status(400).json({ message: 'Cannot delete department with existing employees' });
        }
        
        const [result] = await pool.execute('DELETE FROM department WHERE deptCode = ?', [code]);
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Department not found' });
        }
        
        res.json({ message: 'Department deleted successfully' });
    } catch (error) {
        console.error('Delete department error:', error);
        res.status(500).json({ message: 'Failed to delete department', error: error.message });
    }
};

module.exports = { createDepartment, getAllDepartments, getDepartmentByCode, updateDepartment, deleteDepartment };