const User = require("../../../models").users;
const Profile = require("../../../models").profiles;
const Department = require("../../../models").departments;
const Role = require("../../../models").roles;
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.supervisors =  async (req, res) =>{
    try {
        const supervisors = await Profile.findAll({
            where:{role_id:6},
            attributes:["id","user_id","department_id","firstname","lastname","middlename","createdAt"],
            include: [
              { 
              model: User,
              attributes:["username"]
              },
              { 
                model: Department,
            },
          ],
        });
        const departments = await Department.findAll({where:{active:true}});
        const roles = await Role.findAll({where:{active:true}});
        return res.render("admin/supervisors.ejs", {
            user: req.user, 
            error:false,
            supervisors,
            departments,
            roles,
        })
    } catch (error) {
        console.log(error)
        return res.render("admin/supervisors.ejs", {
            user: req.user, 
            error:error.message,
            supervisors:[],
            departments:[],
            roles:[],
        })
    }
};
exports.oneSupervisor = async (req, res) => {
    try {
        const {id} = req.params;
        const supervisor = await Profile.findOne({
            where:{id},
            attributes:["id","user_id","department_id","firstname","lastname","middlename","createdAt"],
            include: [
            { 
            model: User,
            attributes:["username"]
            },
            { 
                model: Department,
            },
            { 
                model: Role,
                as: "firstRole"
            },
            { 
                model: Role,
                as: "secondRole"
            },
        ],
        });
        return res.status(200).send({success:true, supervisor, message:"Record successfully fetched!"});
    } catch (error) {
        return res.status(500).send({success:false, message:error.message});
    }
};
exports.updateSupervisor = async (req, res) => {
try {
    const { 
        username,
        department,
        firstname,
        lastname,
        role,
     } = req.body;

     const id = req.params.id;
     let roleDetails = await Role.findOne({where:{alias:role}});
     roleDetails = JSON.parse(JSON.stringify(roleDetails))
    //  console.log(roleDetails)
     const profile = await Profile.findOne({where:{user_id:id}})
     if(profile){
        await Profile.update({
            department_id:department,
            firstname,
            lastname, 
            second_role:roleDetails?.id
        },
        {
            where:{user_id:id}
        });
     } 

    const user = await User.update(
        {second_role:roleDetails?.id,username},
        {where:{id}});
    return res.status(200).send({success:true,message:"Record successfully updated!"})
} catch (error) {
    console.log(error)
    return res.status(500).send({success:false,message:error.message})
}


};
exports.cancelSupervisor = async (req, res) => {
    try {
        const { 
            username,
            department,
            firstname,
            lastname,
            role,
         } = req.body;
    
         const id = req.params.id;
         let roleDetails = await Role.findOne({where:{alias:role}});
         roleDetails = JSON.parse(JSON.stringify(roleDetails))
        //  console.log(roleDetails)
         const profile = await Profile.findOne({where:{user_id:id}})
         if(profile){
            await Profile.update({
                department_id:department,
                firstname,
                lastname, 
                second_role:role
            },
            {
                where:{user_id:id}
            });
         } 
    
        const user = await User.update(
            {second_role:role,username},
            {where:{id}});
        return res.status(200).send({success:true,message:"Record successfully updated!"})
    } catch (error) {
        console.log(error)
        return res.status(500).send({success:false,message:error.message})
    }
    
    
    };
exports.createUser = async (req, res) => {
   try {
    const { 
        username,
        department_id,
        firstname,
        lastname,
        role,
        middlename,
        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 password = CryptoJS.AES.encrypt("12345678", key, {iv: iv}).toString();

    let roleDetails = await Role.findOne({where:{alias:role}});
    roleDetails = JSON.parse(JSON.stringify(roleDetails))
    const user = await User.create({
        username,
        password,
        slug:randomString(20),
        role:6,
        second_role:roleDetails?.id,
    });
    const profile = await Profile.create({
        user_id:user.id,
        department_id,
        firstname,
        lastname,
        second_role:roleDetails?.id,
        middlename,
        title,
        role_id:6
    });
    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})
    
   }
};