const express = require('express');
const router = express.Router();
const db = require('../config/db');

// ==========================================
// 1. [CREATE / UPDATE] - Save Department & Salary Tier
// ==========================================
router.post('/', async (req, res) => {
    const { departmentnumber, departmentname, grosssalary } = req.body;
    
    if (!departmentnumber || !departmentname || !grosssalary) {
        return res.status(400).json({ error: "Missing required profile parameters." });
    }

    try {
        // 1. Verify if this Gross Salary tier exists in our base Salary rules matrix
        const [salaryTier] = await db.query(
            'SELECT totaldeduction FROM salary WHERE grosssalary = ?', 
            [Number(grosssalary)]
        );

        // If the array is empty, it means this gross scale grade is completely unknown!
        if (salaryTier.length === 0) {
            return res.status(400).json({ 
                error: `Unknown Gross Salary (${Number(grosssalary).toLocaleString()} RWF). Please formulate this pay scale rule in the Salary Matrix first!` 
            });
        }

        // 2. Since it exists, map the department securely to this existing gross bracket tier asset rule
        await db.query(
            `INSERT INTO department (departmentnumber, departmentname, grosssalary) 
             VALUES (?, ?, ?) 
             ON DUPLICATE KEY UPDATE departmentname = VALUES(departmentname), grosssalary = VALUES(grosssalary)`,
            [departmentnumber, departmentname, Number(grosssalary)]
        );

        res.status(201).json({ message: `Department ${departmentnumber} saved and linked successfully!` });

    } catch (err) {
        console.error("❌ DEPT VERIFICATION POST FAILURE:", err.message);
        res.status(500).json({ error: "Database operation failure", details: err.message });
    }
});
// ==========================================
// 2. [READ ALL] - Fetch All Active Departments
// ==========================================

router.get('/', async (req, res) => {
    try {
        const [rows] = await db.query(`
            SELECT d.departmentnumber, d.departmentname, d.grosssalary, s.totaldeduction, s.netsalary 
            FROM department d
            LEFT JOIN salary s ON d.grosssalary = s.grosssalary
        `);
        res.json(rows);
    } catch (err) { 
        res.status(500).json({ error: err.message }); 
    }
});
// ==========================================
// 3. [READ SINGLE] - Fetch Details for One Department
// ==========================================
router.get('/:id', async (req, res) => {
    try {
        const [rows] = await db.query(`
            SELECT d.departmentnumber, d.departmentname, d.grosssalary, s.totaldeduction, s.netsalary, s.month 
            FROM department d
            LEFT JOIN salary s ON d.grosssalary = s.grosssalary
            WHERE d.departmentnumber = ?`, 
            [req.params.id]
        );
        
        if (rows.length === 0) return res.status(404).json({ error: "Department not found" });
        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// ==========================================
// 4. [DELETE] - Remove a Department
// ==========================================
router.delete('/:id', async (req, res) => {
    try {
        // Find if any employees are linked to this department before deleting it
        const [linkedStaff] = await db.query('SELECT employeenumber FROM employee WHERE departmentnumber = ?', [req.params.id]);
        if (linkedStaff.length > 0) {
            return res.status(400).json({ 
                error: `Cannot delete department. ${linkedStaff.length} employee(s) are currently assigned to it.` 
            });
        }

        await db.query('DELETE FROM department WHERE departmentnumber = ?', [req.params.id]);
        res.json({ message: "Department dropped cleanly from operational assets." });
    } catch (err) {
        console.error("❌ DELETE DEPARTMENT CRASHED:", err.message);
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;