const User = require("../../../models").users;
const Profile = require("../../../models").profiles;
const Roles = require("../../../models").roles;
const Department = require("../../../models").departments;
const CryptoJS = require("crypto-js");
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv  = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
const {randomString} = require("../../helpers/randomString");


exports.adminUser =  async (req, res) =>{
try {
    const { deleted } = req.query;
    const adminUser = await User.findAll({
        where:{
            role:1
        },
        include:[
            {model:Profile},
            {model:Roles, as:"roles"}
        ]
    });

    const roles = await Roles.findAll({where:{active:true}});

    return res.render("admin/adminusers.ejs", 
    {
        users:adminUser,
        roles,
        deleted,
        sessions:req.sessions,
        user: req.user, 
    } )
} catch (error) {
    console.log(error)
    return res.status(500).send({success:false, message:error.message});
}
};
exports.getAdmin = async (req, res) => {
    try {
        const {id} = req.params;
        const supervisor = await Profile.findOne({
            where:{user_id:id},
            attributes:["id","user_id","department_id","firstname","lastname","middlename","createdAt"],
            include: [
            { 
            model: User,
            attributes:["username"]
            },
            { 
                model: Department,
            },
            { 
                model: Roles,
                as: "firstRole"
            },
            { 
                model: Roles,
                as: "secondRole"
            },
        ],
        });
        return res.status(200).send({success:true, supervisor,user: req.user,  message:"Record successfully fetched!"});
    } catch (error) {
        return res.status(500).send({success:false, message:error.message});
    }
};
exports.createUser = async (req, res) => {
    try {
     const { 
         username,
         firstname,
         lastname,
         role,
         middlename,
         password,
         title
      } = req.body;
      
      const checkUser = await User.findOne({where:{username}});
      if(checkUser)
         return res.status(200).send({success:false,message:"User with the username already exist"});
     
     const userPassword = CryptoJS.AES.encrypt(password, key, {iv: iv}).toString();
 
     let roleDetails = await Roles.findOne({where:{alias:role}});
     roleDetails = JSON.parse(JSON.stringify(roleDetails))
     const user = await User.create({
         username,
         password:userPassword,
         slug:randomString(20),
         role:1,
         second_role:roleDetails?.id,
         active:true
     });
     const profile = await Profile.create({
         user_id:user.id,
         firstname,
         lastname,
         second_role:roleDetails?.id,
         middlename,
         title,
         role_id:1
     });
     return res.status(200).send({success:true,message:"User successfully created!", ...user, ...profile})
    } catch (error) {
     console.log(error)
     return res.status(500).send({success:false,message:error.message})
     
    }
};
exports.deleteAdmin = async (req, res) => {
    try {
        const {id} = req.params;
        await User.destroy({where:{id}});
        await Profile.destroy({where:{user_id:id}});
        
        return res.redirect("/admin/admin-user?deleted=true" )
    } catch (error) {
     console.log(error)
     return res.status(500).send({success:false,message:error.message})
    }
};