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

const ContactTags = sequelize.define('contact_tag', {
 id:{type:Sequelize.INTEGER,primaryKey: true,autoIncrement: true,},
 name:{type:Sequelize.CHAR,defaultValue:false,allowNull:false},
 color:{type:Sequelize.CHAR,defaultValue:false,allowNull:false},
 variant:{type:Sequelize.CHAR,defaultValue:false,allowNull:false},
 added_by:{type:Sequelize.INTEGER,defaultValue:false,allowNull:false},
 status:{type:Sequelize.INTEGER,defaultValue:false,allowNull:false},
 timestamp:{type:Sequelize.INTEGER,defaultValue:false,allowNull:false},
},{timestamps:false,tableName:'contact_tag'})

const addContactTags =async(data)=>{
    try {
        let result = await ContactTags.create(data)
        return result.id
    } catch (error) {
        console.log(error)
    }
}

const updateTags=async(data,id)=>{
    let result = await ContactTags.update(data,{
        where:{
            id:id
        },returning:true
    })
    return true
}
const getAllContactTags=async()=>{
    try {
        let result = await sequelize.query(`
        SELECT t.*,CONCAT(u.first_name, ' ', u.last_name) AS authorized_by
        FROM contact_tag t LEFT JOIN 
        users u ON t.added_by = u.id where t.status = 1 
        ORDER BY t.id DESC
    `);
        if(!empty(result)){
            return {
                data: result[0],         
            };
        }else{
            return []
        }
    } catch (error) {
        console.log(error)
    }
} 
const getAllTags=async(search,page,rowPerpage)=>{
    try {
        const offset = (page - 1) * rowPerpage;
        let content = ''
        if(search){
            content=`and t.name LIKE '%${search}%'`
        }
        let result = await sequelize.query(`
        SELECT t.*,CONCAT(u.first_name, ' ', u.last_name) AS authorized_by
        FROM contact_tag t LEFT JOIN 
        users u ON t.added_by = u.id where t.status = 1 ${content}
        ORDER BY t.id DESC
        LIMIT ${rowPerpage} OFFSET ${offset}
    `);
    const countResult = await sequelize.query('SELECT COUNT(id) as count FROM contact_tag where status = 1');
    const totalCount = countResult[0][0].count;
        if(!empty(result)){
            return {
                data: result[0],
                totalCount: totalCount
            };
        }else{
            return []
        }
    } catch (error) {
        console.log(error)
    }
}
const getTagByid = async (id) => {
    try {
        const result = await sequelize.query(
            `SELECT * FROM contact_tag WHERE status=1 AND id=${id}`,         
        );
        return result[0] 
    } catch (error) {
        console.error('Error retrieving tag by ID:', error);
        return []; 
    }
};


const getTagByName = async (name) => {
    try {
        const result = await ContactTags.findOne({
            where: {
                name: name,
                status: 1,
            },
        });
        return result;
    } catch (error) {
        console.error("Error getting tag by name:", error);
        return null;
    }
};

module.exports={
    addContactTags,
    getAllTags,
    getTagByid,
    updateTags,
    getAllContactTags,
    getTagByName,
}