const express = require('express');
const router = express.Router();
const { authenticateToken, authorizePermission } = require('../middleware/auth');
const { pool } = require('../config/database');
// All routes require authentication
router.use(authenticateToken);
// GET /api/designations - Get all designations
router.get('/', authorizePermission('designation.read'), async (req, res) => {
    try {
        const { department_id, parent_id, search } = req.query;
        const isSuperAdmin = (user) => {
            if (!user)
                return false;
            const roleName = (user.role || '').toLowerCase();
            return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
        };
        const parsedRequestedOrg = (() => {
            const v = req.query.organization_id;
            if (v === undefined || v === null || v === '')
                return null;
            const n = Number(v);
            return Number.isNaN(n) ? null : n;
        })();
        const organization_id = isSuperAdmin(req.user) ? (parsedRequestedOrg || null) : (req.user?.organization_id || null);
        let query = `
      SELECT 
        d.id,
        d.name,
        d.organization_id,
        d.department_id,
        d.parent_id,
        d.description,
        d.is_active,
        d.created_at,
        d.updated_at,
        dept.name as department_name,
        parent.name as parent_name
      FROM designations d
      LEFT JOIN departments dept ON d.department_id = dept.id
      LEFT JOIN designations parent ON d.parent_id = parent.id
      WHERE d.is_active = 1
    `;
        const params = [];
        if (organization_id) {
            query += ' AND d.organization_id = ?';
            params.push(organization_id);
        }
        if (department_id) {
            query += ' AND d.department_id = ?';
            params.push(department_id);
        }
        if (parent_id !== undefined) {
            if (parent_id === 'null' || parent_id === '') {
                query += ' AND d.parent_id IS NULL';
            }
            else {
                query += ' AND d.parent_id = ?';
                params.push(parent_id);
            }
        }
        if (search) {
            query += ' AND (d.name LIKE ? OR d.description LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        query += ' ORDER BY d.name ASC';
        const [designations] = await pool.execute(query, params);
        res.json({
            status: 'success',
            data: { designations },
            message: 'Designations fetched successfully'
        });
    }
    catch (error) {
        console.error('Error fetching designations:', error);
        res.status(500).json({
            status: 'error',
            message: 'Failed to fetch designations',
            error: error.message
        });
    }
});
// GET /api/designations/:id - Get single designation
router.get('/:id', authorizePermission('designation.read'), async (req, res) => {
    try {
        const { id } = req.params;
        const isSuperAdmin = (user) => {
            if (!user)
                return false;
            const roleName = (user.role || '').toLowerCase();
            return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
        };
        const parsedRequestedOrg = (() => {
            const v = req.query.organization_id;
            if (v === undefined || v === null || v === '')
                return null;
            const n = Number(v);
            return Number.isNaN(n) ? null : n;
        })();
        const organization_id = isSuperAdmin(req.user) ? (parsedRequestedOrg || null) : (req.user?.organization_id || null);
        let query = `
      SELECT 
        d.id,
        d.name,
        d.organization_id,
        d.department_id,
        d.parent_id,
        d.description,
        d.is_active,
        d.created_at,
        d.updated_at,
        dept.name as department_name,
        parent.name as parent_name
      FROM designations d
      LEFT JOIN departments dept ON d.department_id = dept.id
      LEFT JOIN designations parent ON d.parent_id = parent.id
      WHERE d.id = ? AND d.is_active = 1
    `;
        const params = [id];
        if (organization_id) {
            query += ' AND d.organization_id = ?';
            params.push(organization_id);
        }
        const [designations] = await pool.execute(query, params);
        if (designations.length === 0) {
            return res.status(404).json({
                status: 'error',
                message: 'Designation not found'
            });
        }
        res.json({
            status: 'success',
            data: { designation: designations[0] },
            message: 'Designation fetched successfully'
        });
    }
    catch (error) {
        console.error('Error fetching designation:', error);
        res.status(500).json({
            status: 'error',
            message: 'Failed to fetch designation',
            error: error.message
        });
    }
});
// POST /api/designations - Create new designation
router.post('/', authorizePermission('designation.create'), async (req, res) => {
    try {
        const { name, department_id, parent_id, description } = req.body;
        const isSuperAdmin = (user) => {
            if (!user)
                return false;
            const roleName = (user.role || '').toLowerCase();
            return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
        };
        const bodyOrg = (() => {
            const v = req.body.organization_id;
            if (v === undefined || v === null || v === '')
                return null;
            const n = Number(v);
            return Number.isNaN(n) ? null : n;
        })();
        const organization_id = isSuperAdmin(req.user) ? (bodyOrg || req.user?.organization_id || 1) : (req.user?.organization_id || 1);
        if (!name) {
            return res.status(400).json({
                status: 'error',
                message: 'Designation name is required'
            });
        }
        // Check if designation already exists in the same department
        const [existing] = await pool.execute(`
      SELECT id FROM designations 
      WHERE name = ? AND department_id = ? AND organization_id = ? AND is_active = 1
    `, [name, department_id, organization_id]);
        if (existing.length > 0) {
            return res.status(400).json({
                status: 'error',
                message: 'Designation with this name already exists in the department'
            });
        }
        const [result] = await pool.execute(`
      INSERT INTO designations (name, organization_id, department_id, parent_id, description)
      VALUES (?, ?, ?, ?, ?)
    `, [name, organization_id, department_id || null, parent_id || null, description || null]);
        // Fetch the created designation with related data
        const [newDesignation] = await pool.execute(`
      SELECT 
        d.id,
        d.name,
        d.organization_id,
        d.department_id,
        d.parent_id,
        d.description,
        d.is_active,
        d.created_at,
        d.updated_at,
        dept.name as department_name,
        parent.name as parent_name
      FROM designations d
      LEFT JOIN departments dept ON d.department_id = dept.id
      LEFT JOIN designations parent ON d.parent_id = parent.id
      WHERE d.id = ?
    `, [result.insertId]);
        res.status(201).json({
            status: 'success',
            data: { designation: newDesignation[0] },
            message: 'Designation created successfully'
        });
    }
    catch (error) {
        console.error('Error creating designation:', error);
        res.status(500).json({
            status: 'error',
            message: 'Failed to create designation',
            error: error.message
        });
    }
});
// PUT /api/designations/:id - Update designation
router.put('/:id', authorizePermission('designation.update'), async (req, res) => {
    try {
        const { id } = req.params;
        const { name, department_id, parent_id, description } = req.body;
        const isSuperAdmin = (user) => {
            if (!user)
                return false;
            const roleName = (user.role || '').toLowerCase();
            return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
        };
        const parsedRequestedOrg = (() => {
            const v = req.query.organization_id;
            if (v === undefined || v === null || v === '')
                return null;
            const n = Number(v);
            return Number.isNaN(n) ? null : n;
        })();
        const organization_id = isSuperAdmin(req.user) ? (parsedRequestedOrg || null) : (req.user?.organization_id || null);
        if (!name) {
            return res.status(400).json({
                status: 'error',
                message: 'Designation name is required'
            });
        }
        // Check if designation exists
        let query = 'SELECT id FROM designations WHERE id = ? AND is_active = 1';
        const params = [id];
        if (organization_id) {
            query += ' AND organization_id = ?';
            params.push(organization_id);
        }
        const [existing] = await pool.execute(query, params);
        if (existing.length === 0) {
            return res.status(404).json({
                status: 'error',
                message: 'Designation not found'
            });
        }
        // Check if another designation with same name exists in the same department
        let checkQuery = `
      SELECT id FROM designations 
      WHERE name = ? AND department_id = ? AND id != ? AND is_active = 1
    `;
        const checkParams = [name, department_id, id];
        if (organization_id) {
            checkQuery += ' AND organization_id = ?';
            checkParams.push(organization_id);
        }
        const [duplicate] = await pool.execute(checkQuery, checkParams);
        if (duplicate.length > 0) {
            return res.status(400).json({
                status: 'error',
                message: 'Designation with this name already exists in the department'
            });
        }
        let updateQuery = `
      UPDATE designations 
      SET name = ?, department_id = ?, parent_id = ?, description = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
        const updateParams = [name, department_id || null, parent_id || null, description || null, id];
        if (organization_id) {
            updateQuery += ' AND organization_id = ?';
            updateParams.push(organization_id);
        }
        await pool.execute(updateQuery, updateParams);
        // Fetch the updated designation
        const [updatedDesignation] = await pool.execute(`
      SELECT 
        d.id,
        d.name,
        d.organization_id,
        d.department_id,
        d.parent_id,
        d.description,
        d.is_active,
        d.created_at,
        d.updated_at,
        dept.name as department_name,
        parent.name as parent_name
      FROM designations d
      LEFT JOIN departments dept ON d.department_id = dept.id
      LEFT JOIN designations parent ON d.parent_id = parent.id
      WHERE d.id = ?
    `, [id]);
        res.json({
            status: 'success',
            data: { designation: updatedDesignation[0] },
            message: 'Designation updated successfully'
        });
    }
    catch (error) {
        console.error('Error updating designation:', error);
        res.status(500).json({
            status: 'error',
            message: 'Failed to update designation',
            error: error.message
        });
    }
});
// DELETE /api/designations/:id - Soft delete designation
router.delete('/:id', authorizePermission('designation.delete'), async (req, res) => {
    try {
        const { id } = req.params;
        const isSuperAdmin = (user) => {
            if (!user)
                return false;
            const roleName = (user.role || '').toLowerCase();
            return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
        };
        const parsedRequestedOrg = (() => {
            const v = req.query.organization_id;
            if (v === undefined || v === null || v === '')
                return null;
            const n = Number(v);
            return Number.isNaN(n) ? null : n;
        })();
        const organization_id = isSuperAdmin(req.user) ? (parsedRequestedOrg || null) : (req.user?.organization_id || null);
        // Check if designation exists
        let query = 'SELECT id FROM designations WHERE id = ? AND is_active = 1';
        const params = [id];
        if (organization_id) {
            query += ' AND organization_id = ?';
            params.push(organization_id);
        }
        const [existing] = await pool.execute(query, params);
        if (existing.length === 0) {
            return res.status(404).json({
                status: 'error',
                message: 'Designation not found'
            });
        }
        // Check if designation is being used by any users
        let userQuery = 'SELECT id FROM users WHERE designation_id = ? AND is_active = 1';
        const userParams = [id];
        if (organization_id) {
            userQuery += ' AND organization_id = ?';
            userParams.push(organization_id);
        }
        const [users] = await pool.execute(userQuery, userParams);
        if (users.length > 0) {
            return res.status(400).json({
                status: 'error',
                message: 'Cannot delete designation as it is being used by users'
            });
        }
        // Soft delete
        let deleteQuery = 'UPDATE designations SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?';
        const deleteParams = [id];
        if (organization_id) {
            deleteQuery += ' AND organization_id = ?';
            deleteParams.push(organization_id);
        }
        await pool.execute(deleteQuery, deleteParams);
        res.json({
            status: 'success',
            message: 'Designation deleted successfully'
        });
    }
    catch (error) {
        console.error('Error deleting designation:', error);
        res.status(500).json({
            status: 'error',
            message: 'Failed to delete designation',
            error: error.message
        });
    }
});
module.exports = router;
//# sourceMappingURL=designations.js.map