const sequelize = require("../config/dbconnection")
const Sequelize = require('sequelize')
const {TWILIO_PHONE} = require('../constants/constant')
const twilio = require('../models/twilio')

const getAllCalls = async (where='',order='DESC', limit=false) => {
    let sql = `SELECT tc.*,concat(u.first_name,' ',u.last_name) AS from_user, concat(u2.first_name,' ',u2.last_name) AS to_user`+
    ` FROM twilio_calls tc`+
    ` LEFT JOIN users u ON tc.from_user_id=u.id`+
    ` LEFT JOIN users u2 ON tc.to_user_id=u2.id`+
    ` WHERE tc.status = 1`+
    ` AND tc.direction != "outbound-api"`+
    ` AND tc.from != "client:support_agent"`+
    ` AND (tc.from='${TWILIO_PHONE}' OR tc.to='${TWILIO_PHONE}')`
    
    if(where){
        sql += where
    }

    sql += ` ORDER BY tc.start_time ${order}`

    if(limit){
        sql += ` LIMIT ${limit}`;
    }
    const result = await sequelize.query(sql);  
    if(result){
        if(result[0].length > 0){
            return result[0];
        }else{
            return false;
        }
    }else{
        return false;
    }		
}

const getAllSms = async (where='',order='DESC') => {
    let whereCondition={};
    if(where){
        whereCondition[Sequelize.Op.or] = [Sequelize.literal(`from = '+${where}'`), Sequelize.literal(`to = '+${where}'`)];
    }
    try{
        // console.log("whereCondition",whereCondition);
        const result = await twilio.TwilioSms.findAll({
            where:{
                status:1,
                [Sequelize.Op.and]: whereCondition,
            },
            order : [ ['date_created', order] ]
        })
        if(result){
            return result;
        }else{
            return false;
        }
    }catch(error){
        console.log("getAllSms error",error);
    }	
}

module.exports = { getAllCalls, getAllSms }