const departmentModel = require('../models/department');
const { portalName } = require("../constants/constant");
const Admin = require ('../models/admin')
const moment = require("moment");

const getAllDepartments = async(req,res) => {
    try{
        let departments = await departmentModel.getAllDepartments();
        res.send({status:1,message:"Data fetched successully",result:departments});
    }
    catch(error){
        console.log(error);
        res.send({status:0,message:"Error fetching data"});
    }
}

const getDepartmentById = async(req,res) => {
    try{
        let {id} = req.body;
        let departments = await departmentModel.getDepartmentByIdForEdit(id);
        res.send({status:1,message:"Data fetched successully",result:departments[0]});
    }
    catch(error){
        console.log(error);
        res.send({status:0,message:"Error fetching data"});
    }
}

const addDepartment = async(req,res) => {
    try{
        let currentDate = Math.round(moment().valueOf() / 1000);
        let deptData={};
	    deptData['name']   = req.body.name;
	    deptData['forward_number']   = req.body.forward_number;
		deptData['added_by']   = req.body.userId;
		deptData['added_time']   = currentDate;
		deptData['updated_by'] = req.body.userId;
		deptData['updated_time']   = currentDate;
		deptData['status']   = 1;

        let modelStatus = await departmentModel.addDepartment(deptData);
		if(modelStatus){
            // Notification
            let notificationMsg=`Department "${deptData['name']}" has been added to ${portalName}.`;
            let notificationUrl="departments";
            // Alert to user of new added department
            const incrementResult_User = await Admin.incrementField(deptData['added_by'],"noti_count",1);
            let notificationData_user = {
                user_id: deptData['added_by'],
                url: notificationUrl,
                timestamp: currentDate,
                message: notificationMsg,
                status: 1,
                from_id: deptData['added_by'],
            };
            const addNotificationResult_user = await Admin.addNotification(notificationData_user);
            // Alert to admins of new added department
            let adminIds = await Admin.getAllAdminIds();
            let notificationData = {};
            for (const adminId of adminIds) {
                if (adminId != deptData['added_by']) {
                    const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                    notificationData = {
                        user_id: adminId,
                        url: notificationUrl,
                        timestamp: currentDate,
                        message: notificationMsg,
                        status: 1,
                        from_id: deptData['added_by'],
                    };
                    const addNotificationResult = await Admin.addNotification(notificationData);
                }
            }
            res.send({status:1,message:"Department added successfully"});
	    }else{
            res.send({status:0,message:"Failed to add department"});
	    } 
    }
    catch(error){
        console.log(error);
        res.send({status:500,message:"Server Error"});
    }
}

const editDepartment = async (req,res) => {
    try{
        let currentDate = Math.round(moment().valueOf() / 1000);
        let {id} = req.body;
        let deptData={};
	    deptData['name'] = req.body.name;
	    deptData['forward_number'] = req.body.forward_number;
		deptData['updated_by'] = req.body.userId;
		deptData['updated_time'] = currentDate;
		deptData['status'] = 1;
        let modelStatus = await departmentModel.updateDepartment(id,deptData);
		if(modelStatus){
            // Notification
            let notificationMsg=`The details of department "${deptData['name']}" has been updated.`;
            let notificationUrl="departments";
            // Alert to user of new added department
            const incrementResult_User = await Admin.incrementField(deptData['updated_by'],"noti_count",1);
            let notificationData_user = {
                user_id: deptData['updated_by'],
                url: notificationUrl,
                timestamp: currentDate,
                message: notificationMsg,
                status: 1,
                from_id: deptData['updated_by'],
            };
            const addNotificationResult_user = await Admin.addNotification(notificationData_user);
            // Alert to admins of new added department
            let adminIds = await Admin.getAllAdminIds();
            let notificationData = {};
            for (const adminId of adminIds) {
                if (adminId != deptData['updated_by']) {
                    const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                    notificationData = {
                        user_id: adminId,
                        url: notificationUrl,
                        timestamp: currentDate,
                        message: notificationMsg,
                        status: 1,
                        from_id: deptData['updated_by'],
                    };
                    const addNotificationResult = await Admin.addNotification(notificationData);
                }
            }
            res.send({status:1,message:`Department "${deptData['name']}" updated successfully`});
	    }else{
            res.send({status:0,message:"Failed to update department"});
	    } 
    }
    catch(error){
        console.log(error);
        res.send({status:500,message:"Server Error"});
    }
}

const deleteDepartment = async (req,res) => {
    try{
        let currentDate = Math.round(moment().valueOf() / 1000);
        let {id, status, userId} = req.body;
        let data={};
        let notificationMsg;
        data['status']=status;
        if(id){
            let deleted = await departmentModel.updateDepartment(id,data);
            let deptData= await departmentModel.getDepartmentByIdForEdit(id);
            if(data['status'] === 2){
                notificationMsg=`The department "${deptData[0]['name']}" has been deleted.`;
            }else if(data['status'] === 0){
                notificationMsg=`The department "${deptData[0]['name']}" has been made inactive.`;
            }else{
                notificationMsg=`The department "${deptData[0]['name']}" has been made active.`;
            }
            if(deleted){
                // Notification
                let notificationUrl="departments";
                // Alert to user of new added department
                const incrementResult_User = await Admin.incrementField(userId,"noti_count",1);
                let notificationData_user = {
                    user_id: userId,
                    url: notificationUrl,
                    timestamp: currentDate,
                    message: notificationMsg,
                    status: 1,
                    from_id: userId,
                };
                const addNotificationResult_user = await Admin.addNotification(notificationData_user);
                // Alert to admins of new added department
                let adminIds = await Admin.getAllAdminIds();
                let notificationData = {};
                for (const adminId of adminIds) {
                    if (adminId != userId) {
                        const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                        notificationData = {
                            user_id: adminId,
                            url: notificationUrl,
                            timestamp: currentDate,
                            message: notificationMsg,
                            status: 1,
                            from_id: userId,
                        };
                        const addNotificationResult = await Admin.addNotification(notificationData);
                    }
                }
                res.send({status:1,message:notificationMsg});
            }else{
                res.send({status:0,message:"Unable to delete the department!"});
            }
        } 
    }
    catch(error){
        console.log(error);
        res.send({status:500,message:"Server Error"});
    }
}

module.exports = { getAllDepartments, getDepartmentById, addDepartment, editDepartment, deleteDepartment }