const sequelize = require("../config/dbconnection");
const Sequelize = require("sequelize");
const Admin = require("../models/admin");
const { empty, getAgoString } = require("../Helpers/Common");

const TaskMember = sequelize.define('staff_task_members', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    taskid:{type:Sequelize.INTEGER,allowNull:false},
    userid:{type:Sequelize.INTEGER,allowNull:false},
},
{timestamps:false})

const addtaskMember= async(data)=>{
    try {
        let result = await TaskMember.create(data)
        return result.id
    } catch (error) {
        console.log(error)
    }
}
const removeTaskMember=async(uid,id)=>{
    try {
        let result = await sequelize.query(`
        DELETE FROM staff_task_members WHERE userid = ${uid} AND taskid=${id};
        `)
    } catch (error) {
        console.log(error)
    }
} 

const getTaskmembers=async(id)=>{
 try {
    let result = await sequelize.query(`
    SELECT users.id as userid, CONCAT(users.first_name, ' ', users.last_name) as username, users.profile_pic,
       users.email, users.email_notification, users.active,
       staff_task_members.ID
    FROM staff_task_members
    JOIN users ON users.id = staff_task_members.userid
    WHERE staff_task_members.taskid = ${id};
    `)
    if(result){
        const data = result.map((row) => row);
        return data;
    }else{
        return false
    }
 } catch (error) {
  console.log(error)  
 }
}
// const getuserDetailById=async(id)=>{
//     try {
//         let result = await sequelize.query(`
//         SELECT id ,concat(first_name,' ',last_name) as username,username as email,email_notification FROM users 
//         WHERE id =${id}
//         `)
//         if(!empty(result)){
//             if(result.length==1) {
//              const data = result.map((row) => row);
//              return data;
//             }else{
//              return false
//             }
//          }
//     } catch (error) {
//         console.log(error)
//     }
// }

const getuserDetailById = async (id) => {
    try {
        let result = await sequelize.query(`
            SELECT id, CONCAT(first_name, ' ', last_name) AS username, username AS email, email_notification 
            FROM users 
            WHERE id = :id
        `, {
            replacements: { id },
            type: sequelize.QueryTypes.SELECT
        });

        // Check if result is not empty and has only one record
        if (result && result.length === 1) {
            // Assuming you just need the first result
            return result[0]; // Return the first user data (email and username)
        } else {
            return false; // No user found or more than one result
        }
    } catch (error) {
        console.log(error);
        return false; // Return false in case of an error
    }
}


module.exports={
    addtaskMember,
    getTaskmembers,
    getuserDetailById,
    removeTaskMember,
}