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

// [CREATE] - Add Employee record
router.post('/', async (req, res) => {
    const { firstname, lastname, position, address, telephone, gender, hireddate, departmentnumber } = req.body;
    try {
        await db.query(
            `INSERT INTO employee (firstname, lastname, position, address, telephone, gender, hireddate, departmentnumber) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
            [firstname, lastname, position, address, telephone, gender, hireddate, departmentnumber || null]
        );
        res.status(201).json({ message: "Employee registered dynamically" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [READ ALL] - Fetch whole corporate workforce roster
router.get('/', async (req, res) => {
    try {
        const [rows] = await db.query(`
            SELECT e.*, d.departmentname, s.netsalary 
            FROM employee e 
            LEFT JOIN department d ON e.departmentnumber = d.departmentnumber
            LEFT JOIN salary s ON d.grosssalary = s.grosssalary
        `);
        res.json(rows);
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [READ SINGLE] - Fetch one single target employee record 
router.get('/:id', async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM employee WHERE employeenumber = ?', [req.params.id]);
        if (rows.length === 0) return res.status(404).json({ error: "Employee record missing" });
        res.json(rows[0]);
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [UPDATE] - Overwrite properties on staff record profile file
router.put('/:id', async (req, res) => {
    const { firstname, lastname, position, address, telephone, gender, hireddate, departmentnumber } = req.body;
    try {
        await db.query(
            `UPDATE employee SET firstname = ?, lastname = ?, position = ?, address = ?, 
             telephone = ?, gender = ?, hireddate = ?, departmentnumber = ? WHERE employeenumber = ?`,
            [firstname, lastname, position, address, telephone, gender, hireddate, departmentnumber, req.params.id]
        );
        res.json({ message: "Staff record profile overwrote cleanly" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [DELETE] - Erase employee entry boundary record row
router.delete('/:id', async (req, res) => {
    try {
        await db.query('DELETE FROM employee WHERE employeenumber = ?', [req.params.id]);
        res.json({ message: "Staff file data expunged securely" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

module.exports = router;