const sequelize = require("../config/dbconnection");
const Sequelize = require("sequelize");
const { Users } = require("./admin");
const { Op } = Sequelize;
const {TWILIO_PHONE} = require('../constants/constant')
const { Department } = require('../models/department')
const {Contacts}=require("../models/contacts")

const TwilioCallFlows = sequelize.define(
  "twilio_call_flows",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    welcome_text: { type: Sequelize.STRING, allowNull: false },
    need_menu: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
    menu_message: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    enable_non_working_hours: {
      type: Sequelize.INTEGER,
      allowNull: false,
      defaultValue: 0,
    },
    enable_non_working_days: {
      type: Sequelize.INTEGER,
      allowNull: false,
      defaultValue: 0,
    },
    start_day: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
    end_day: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 7 },
    start_time: {
      type: Sequelize.INTEGER,
      allowNull: true,
      defaultValue: null,
    },
    end_time: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    added_by: { type: Sequelize.INTEGER, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.INTEGER, allowNull: true, defaultValue: 1 },
  },
  { timestamps: false }
);

const TwilioCallSettings = sequelize.define(
  "twilio_call_settings",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    name: { type: Sequelize.STRING, allowNull: false },
    value: { type: Sequelize.TEXT, allowNull: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
  },
  { timestamps: false }
);

const TwilioCallFlowMenu = sequelize.define(
  "twilio_call_flow_menus",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    twilio_call_flow_id: { type: Sequelize.INTEGER, allowNull: false },
    press_value: { type: Sequelize.INTEGER, allowNull: false },
    department_id: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
  },
  { timestamps: false }
);

const TwilioCallRecordings = sequelize.define(
  "twilio_call_recordings",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    call_sid: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    conference_sid: { type: Sequelize.STRING, allowNull: false },
    recording_sid: { type: Sequelize.STRING, allowNull: false },
    recording_url: { type: Sequelize.TEXT, allowNull: false },
    recording_status: { type: Sequelize.STRING, allowNull: false },
    recording_duration: { type: Sequelize.INTEGER, allowNull: false },
    recording_channels: { type: Sequelize.INTEGER, allowNull: false },
    recording_start_time: {
      type: Sequelize.INTEGER,
      allowNull: true,
      defaultValue: null,
    },
    recording_source: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    local_file_name: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    downloaded: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0 },
    timestamp: { type: Sequelize.INTEGER, allowNull: false },
    status: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 },
  },
  { timestamps: false }
);

const TwilioCalls = sequelize.define(
  "twilio_calls",
  {
    id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    from_user_id: { type: Sequelize.INTEGER, allowNull: true, defaultValue:null },
    to_user_id: { type: Sequelize.INTEGER, allowNull: true, defaultValue:null },
    to: { type: Sequelize.STRING, allowNull: false },
    from: { type: Sequelize.STRING, allowNull: false },
    forwarded_from: { type: Sequelize.STRING, allowNull: true, defaultValue:null },
    direction: { type: Sequelize.STRING, allowNull: false },
    duration: { type: Sequelize.INTEGER, allowNull: false, defaultValue : 0 },
    start_time: { type: Sequelize.INTEGER, allowNull: false },
    end_time: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    group_sid: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    parent_call_sid: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    phone_number_sid: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    price: { type: Sequelize.DOUBLE, allowNull: false, defaultValue: 0.00000	},
    price_unit: { type: Sequelize.STRING, allowNull: false, defaultValue: "USD" },
    sid: { type: Sequelize.STRING, allowNull: false },
    conference_sid: {
      type: Sequelize.STRING,
      allowNull: true,
      defaultValue: null,
    },
    date_created: {
      type: Sequelize.INTEGER,
      allowNull: false,
    },
    date_updated: {
      type: Sequelize.INTEGER,
      allowNull: false,
    },
    call_status: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
  },
  { timestamps: false }
);

TwilioCalls.belongsTo(Users, { foreignKey: 'from_user_id', as: 'fromUser' });
TwilioCalls.belongsTo(Users, { foreignKey: 'to_user_id', as: 'toUser' });

const TwilioSms = sequelize.define('twilio_sms', {
  id: {
    type: Sequelize.INTEGER,
    allowNull:false,
    primaryKey: true,
    autoIncrement: true,
  },
  user_id: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
  },
  partner_id: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
  },
  contact_id: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
  },
  lead_id: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
  },
  to: {
    type: Sequelize.STRING(30),
    allowNull: false,
  },
  from: {
    type: Sequelize.STRING(30),
    allowNull: false,
  },
  message_body: {
    type: Sequelize.TEXT,
    allowNull: true,
    defaultValue: null,
  },
  direction: {
    type: Sequelize.STRING(60),
    allowNull: false,
  },
  price: {
    type: Sequelize.DOUBLE(15, 5),
    allowNull: false,
    defaultValue: 0.00000,
  },
  price_unit: {
    type: Sequelize.STRING(10),
    allowNull: false,
    defaultValue: 'USD',
  },
  sid: {
    type: Sequelize.STRING(200),
    allowNull: false,
  },
  date_created: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  date_updated: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  sms_status: {
    type: Sequelize.STRING(30),
    allowNull: false,
  },
  status: {
    type: Sequelize.TINYINT(2),
    allowNull: false,
    defaultValue: 1,
  },
}, {
  timestamps: false,
  underscored: true, // Use underscores in the table and column names
});

const TwilioConference = sequelize.define('twilio_conferences', {
  id: {
    type: Sequelize.INTEGER,
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
  },
  friendly_name: {
    type: Sequelize.STRING(200),
    allowNull: false,
  },
  team_user_id: {
    type: Sequelize.INTEGER,
    allowNull:true,
    defaultValue: null,
  },
  partner_id: {
    type: Sequelize.INTEGER,
    allowNull:true,
    defaultValue: null,
  },
  contact_id: {
    type: Sequelize.INTEGER,
    allowNull:true,
    defaultValue: null,
  },
  lead_id: {
    type: Sequelize.INTEGER,
    allowNull:true,
    defaultValue: null,
  },
  direction: {
    type: Sequelize.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '1 - IN',
  },
  sid: {
    type: Sequelize.STRING(200),
    allowNull: false,
  },
  reason_conference_ended: {
    type: Sequelize.TEXT,
    allowNull:true,
    defaultValue:null,
  },
  call_sid_ending_conference: {
    type: Sequelize.STRING(200),
    allowNull:true,
    defaultValue: null,
  },
  date_created: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  date_updated: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  call_status: {
    type: Sequelize.STRING(30),
    allowNull: false,
  },
  status: {
    type: Sequelize.TINYINT,
    allowNull: false,
    defaultValue: 1,
  },
}, {
  timestamps: false,
  tableName: 'twilio_conferences',
});

const addCallRecording = async (data) => {
  try {
    const createdRecording = await TwilioCallRecordings.create({ data });
    return createdRecording.id;
  } catch (error) {
    console.error("Error adding call recording:", error.message);
    throw error;
  }
};

const updateCallRecording = async (id, data) => {
  try {
    const [affectedRows] = await TwilioCallRecordings.update(data, {
      where: { id },
    });
    return affectedRows > 0;
  } catch (error) {
    console.error("Error updating call recording:", error.message);
    throw error;
  }
};

const updateTwilioCall = async (sid, data) => {
  try {
    const [affectedRows] = await TwilioCalls.update(data, {
      where: { sid },
    });
    console.log("updatedddddddddddddddddddd");
    return affectedRows > 0;
  } catch (error) {
    console.error("Error updating Twilio call:", error.message);
    throw error;
  }
};

const addTwilioCalls = async (data) => {
  try {
    const sid = data.sid;
    const existingRecord = await TwilioCalls.findOne({
      where: {
        [Op.or]: [{ sid }, { parent_call_sid: sid }],
      },
    });

    if (!existingRecord) {
      console.log("creatinggggggggggggggggggggggggggggg");
      const createdRecord = await TwilioCalls.create(data);
      return createdRecord.id;
    } else {
      console.log("updatingggggggggggggggggggggggggggggggggg");
      delete data.from_user_id;
      delete data.to_user_id;
      await updateTwilioCall(data.sid, data);
      return existingRecord.id;
    }
  } catch (error) {
    console.error("Error adding Twilio calls:", error.message);
    throw error;
  }
};

const getAllCallLogs = async (whereArray = '', order = 'DESC', limit = false) => {
    try {
      const whereCondition = {
        status: 1,
        direction: {[Op.ne]:'outbound-api'},
        from: { [Op.ne]: 'client:support_agent' },
        // [Op.or]: [{ from: TWILIO_PHONE }, { to: TWILIO_PHONE }],
        [Op.or]: [{ forwarded_from: TWILIO_PHONE }, { from: TWILIO_PHONE }, { to: TWILIO_PHONE }],
        [Sequelize.Op.and]: whereArray,
      };
      console.log("whereCondition",whereCondition);
      const queryOptions = {
        include: [
          { model: Users, as: 'fromUser', attributes: ['first_name', 'last_name'] },
          { model: Users, as: 'toUser', attributes: ['first_name', 'last_name'] },
        ],
        where: whereCondition,
        order: [['start_time', order]],
      };
  
      if (limit) {
        queryOptions.limit = limit;
      }
  
      const result = await TwilioCalls.findAll(queryOptions);
  
      if (result.length > 0) {
        return result;
      } else {
        return false;
      }
    } catch (error) {
      console.error('Error fetching all calls:', error.message);
      throw error;
    }
};

const getCallSettings = async () => {
  try {
    const settings = await TwilioCallSettings.findAll({
      order: [['id', 'DESC']],
    });

    const data = {};
    if (settings.length >= 1) {
      settings.forEach((setting) => {
        data[setting.name] = setting.value;
      });
    }

    return data;
  } catch (error) {
    console.error('Error fetching call settings:', error.message);
    throw error;
  }
};

const updateCallSettings = async (data) => {
  try {
    const promises = Object.keys(data).map(async (name) => {
      const value = data[name];

      const [affectedRows] = await TwilioCallSettings.update({ value }, {
        where: { name },
      });

      return { name, affectedRows };
    });

    const results = await Promise.all(promises);

    const updatedSettings = results.filter(result => result.affectedRows > 0)
      .map(result => result.name);

    return updatedSettings;
  } catch (error) {
    console.error('Error updating call settings:', error.message);
    throw error;
  }
};

const getAllSmsList = async (where='',order='DESC') => {
  let whereCondition='';
  if(where){
    whereCondition = where;
  }
  console.log("whereCondition",whereCondition);
  // const result = await TwilioSms.findAll({
  //   where:{
  //     status:1,
  //     [Sequelize.Op.and]: whereCondition,
  //   },
  //   include: [
  //     {
  //       model: Contacts,
  //       on: {
          
  //         id: Sequelize.literal('"TwilioSms"."contact_id"'),
  //         // Target key in the Contacts table
  //         name: Sequelize.literal('"contacts"."name"'),
  //       },
  //     },
  //   ],
  //   order : [
  //     ['date_created', order],
  //   ]
  // })
  let result=await sequelize.query('select t.*, c.name as contact_name, p.name as partner_name,l.name as lead_name from twilio_sms t'
  +` left join contacts c on c.id = t.contact_id `
  +` left join partners p on p.id = t.partner_id `
  +` left join leads l on l.id = t.lead_id `
  +` where t.status=1 ${whereCondition}`
  +` order by date_created ${order}`)
  if(result[0]){
    return result[0];
  }else{
    return false;
  }		
}

const getActiveCallFlow = async () => {
  try {
    // const data = await TwilioCallFlows.findOne({
    //   where: { status: 1 },
    //   order: [["id", "DESC"]],
    //   include: [
    //     {
    //       model: TwilioCallFlowMenu,
    //       where: { status: 1 },
    //       attributes: ["press_value", "department_id"],
    //       order: [["id", "ASC"]],
    //     },
    //   ],
    // });
let query=await  sequelize.query(` SELECT * FROM twilio_call_flows WHERE status=1 ORDER BY id DESC LIMIT 1`)
let data=[]
if(query[0].length===1){
  data=query[0][0]
  let  query1=await  sequelize.query(`SELECT tc.press_value,tc.department_id,d.name as department_name,d.forward_number FROM twilio_call_flow_menus tc left join departments d on d.id=tc.department_id WHERE tc.status=1 and tc.twilio_call_flow_id=${data['id']} ORDER BY tc.id ASC`)		;
  if(query1[0].length>0)
  {
    data['call_flow_menus']=query1[0];
  }		
  
}
    // if (data) {
    //   // Sequelize automatically converts the result to JSON, so no need to use row_array()
    //   return data.toJSON();
    // }

    return data;
  } catch (error) {
    console.error("Error getting active call flow:", error);
    throw error;
  }
};

const getForwardNumberOfAvailableWorker = async (calledWorkerSid) => {
  try {
    // const data = await TwilioCallFlows.findOne({
    //   where: { status: 1 },
    //   order: [["id", "DESC"]],
    //   include: [
    //     {
    //       model: TwilioCallFlowMenu,
    //       where: { status: 1 },
    //       attributes: ["press_value", "department_id"],
    //       order: [["id", "ASC"]],
    //     },
    //   ],
    // });
    let query=await sequelize.query(` SELECT * FROM twilio_call_flows WHERE status=1 ORDER BY id DESC LIMIT 1`)
    let data=[]
    if(query[0].length===1){
      data=query[0][0]
      let  query1=await  sequelize.query(`SELECT tc.press_value,tc.department_id,d.name as department_name,concat(sm.first_name,' ',sm.last_name) AS staffname,sm.forward_no `
      +` FROM twilio_call_flow_menus tc `
      +` left join departments d on d.id=tc.department_id `
      +` left join users u on u.department_id=tc.department_id `
      +` left join staff_members sm on sm.user_id = u.id`
      +` WHERE tc.status=1 AND tc.twilio_call_flow_id=${data['id']} AND u.worker_sid = "${calledWorkerSid}"`
      +` ORDER BY tc.id ASC`);
      if(query1[0].length>0)
      {
        data['call_flow_menus']=query1[0];
      }
    }
    return data;
  } catch (error) {
    console.error("Error getting active call flow:", error);
    throw error;
  }
};

const getAllRecordings = async () => {
  const result = await sequelize.query(`SELECT tc.*,r.id AS record_id, r.call_sid, r.recording_sid, r.recording_duration, `+
  ` r.recording_url, r.local_file_name, concat(u.first_name,' ',u.last_name) AS from_user, concat(u2.first_name,' ',u2.last_name) AS to_user`+
  ` FROM twilio_call_recordings r`+
  ` LEFT JOIN twilio_calls tc ON r.call_sid=tc.parent_call_sid OR r.call_sid=tc.sid`+
  ` LEFT JOIN users u ON tc.from_user_id=u.id`+
  ` LEFT JOIN users u2 ON tc.to_user_id=u2.id`+
  ` WHERE r.status = 1`+
  ` AND tc.from IS NOT NULL`+
  ` ORDER BY r.recording_start_time DESC`);
  if(result){
    if(result[0].length>0){
      return result[0]
    }
    else{
      return false
    }
  }
  else{
    return false
  }
}

const getTotalCalls = async (direction = null, status = null, startTime = null, endTime = null) => {
  try {
    const queryOptions = {
      attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'count']],
    };
    if (direction) {
      queryOptions.where = {
        ...queryOptions.where,
        direction: { [Op.eq]: direction },
      };
    }else{
      queryOptions.where = {
        ...queryOptions.where,
        direction: { [Op.ne]: 'outbound-api' },
      };
    }

    if (status) {
      queryOptions.where = { ...queryOptions.where, 
        call_status: { [Op.or]: ['completed', 'in-progress'] }, };

      if (status === "(call_status='completed' OR call_status='in-progress')") {
        queryOptions.where = {
          ...queryOptions.where,
          direction: { [Op.or]: ['inbound', 'outbound-dial'] },
        };
      }
    }

    if (startTime) {
      queryOptions.where = {
        ...queryOptions.where,
        start_time: { [Op.gte]: startTime },
      };
    }

    if (endTime) {
      queryOptions.where = {
        ...queryOptions.where,
        start_time: { [Op.lte]: endTime },
      };
    }

    queryOptions.where = {
      ...queryOptions.where,
      from: { [Op.ne]: 'client:support_agent' },
    };

    const result = await TwilioCalls.findAll(queryOptions);

    if (result) {
      return result[0].dataValues.count;
    } else {
      return 0;
    }
  } catch (error) {
    console.error('Error getting total calls:', error.message);
    throw error;
  }
}

const totalMissedCalls = async (startTime = null, endTime = null) => {
  try {
    const queryOptions = {
      attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'count']],
      where: {
        call_status: {
          [Op.in]: ['no-answer', 'busy', 'failed', 'canceled','ringing'],
        },
        direction: { [Op.ne]: 'outbound-api' },
        from: { [Op.ne]: 'client:support_agent' },
      },
    };

    if (startTime) {
      queryOptions.where = {
        ...queryOptions.where,
        start_time: { [Op.gte]: startTime },
      };
    }

    if (endTime) {
      queryOptions.where = {
        ...queryOptions.where,
        start_time: { [Op.lte]: endTime },
      };
    }

    const result = await TwilioCalls.findOne(queryOptions);

    if (result) {
      return result.dataValues.count;
    } else {
      return 0;
    }
  } catch (error) {
    console.error('Error getting total missed calls:', error.message);
    throw error;
  }
}

const getTotalTalkTime = async (direction = null) => {
  try {
    const queryOptions = {
      attributes: [[sequelize.fn('SUM', sequelize.col('duration')), 'count']],
      where: {
        call_status: 'completed',
        direction: { [Op.ne]: 'outbound-api' },
        from: { [Op.ne]: 'client:support_agent' },
      },
    };

    if (direction) {
      queryOptions.where = {
        ...queryOptions.where,
        direction,
      };
    }

    const result = await TwilioCalls.findOne(queryOptions);

    if (result) {
      const totalTalkTimeArray = secondsToTime(result.dataValues.count);
      let totalTalkTime = '';
      
      if (totalTalkTimeArray.d) {
        totalTalkTime += totalTalkTimeArray.d + 'd';
      }
      if (totalTalkTimeArray.h) {
        totalTalkTime += totalTalkTimeArray.h + 'h ';
      }
      if (totalTalkTimeArray.m) {
        totalTalkTime += totalTalkTimeArray.m + 'm ';
      }
      if (totalTalkTimeArray.s) {
        totalTalkTime += totalTalkTimeArray.s + 's';
      }
      // console.log('result---------------------',result);
      return { text: totalTalkTime, seconds: result.dataValues.count ? parseInt(result.dataValues.count) : 0 };
    } else {
      return 0;
    }
  } catch (error) {
    console.error('Error getting total talk time:', error.message);
    throw error;
  }
}

const secondsToTime = (seconds) => {
  const d = Math.floor(seconds / (3600 * 24));
  const h = Math.floor((seconds % (3600 * 24)) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);

  return { d, h, m, s };
}

const getAllDepartments = async () => {
  try{
    const result = await Department.findAll({
      attributes : ['id','name'],
      where:{
        status : 1,
      },
      order:[['id','DESC']]
    });
    return result;
  }
  catch(error){
    console.log(error);
    return false;
  }
}

const getAgentsByDepartment = async (departmentId,userId) => {
  try{
    let where={};
    if(departmentId){
      where.department_id = departmentId;
    }
    const result = await Users.findAll({
      attributes : ['id', 'first_name', 'last_name', 'profile_pic', 'worker_sid', 'department_id', 'active'],
      where : {
        status : 1,
        worker_sid: { [Sequelize.Op.not]: null },
        [Sequelize.Op.and]: where,
        id: { [Op.ne]: userId },
      },
      order : [['id','DESC']]
    });
    const dataPromises = result.map(async (row) => {
      const liveCall = await getLiveCall(row.id);
      return {
          ...row.dataValues,
          live_call: liveCall,
      };
  });
  const data = await Promise.all(dataPromises);
  return data;
  }
  catch(error){
    console.log(error);
    return false;
  }
}

const getLiveCall = async (teamUserId) => {
  // console.log("teamUserId$$$$$$$$$$$$$$$$$$$",teamUserId);
  const result = await sequelize.query (`SELECT tc.*, p.name as partner_name, c.name as contact_name, l.name as lead_name,`+
        ` p.phone as partner_phone, c.phone as contact_phone, l.phone as lead_phone`+
        ` FROM twilio_conferences tc `+
        ` left join users u on u.id=tc.team_user_id`+
        ` left join partners p on p.id=tc.partner_id`+
        ` left join contacts c on c.id=tc.contact_id`+
        ` left join leads l on l.id=tc.lead_id`+
        ` WHERE tc.team_user_id=${teamUserId} and tc.call_status='in-progress' `); 
  
  if(result){
    if(result[0].length === 1){
      return result[0];
    }else{
      return false;
    }
  }else{
    return false;
  }
}

const getAllCallFlows = async () => {
  let query = await TwilioCallFlows.findAll({
    where : { status : {[Op.ne] : 2} },
    order : [ [ "id", "DESC" ] ],
  });
  if(query){
    return query;
  }
}

const addCallFlow = async (data) => {
  try{
    let result = await TwilioCallFlows.create(data);
    return result.id;
  }
  catch(error){
    console.log("Error",error);
  }
}

const getCallFlowById = async (id) => {
  try{
    const callFlow  = await TwilioCallFlows.findOne({
      where: { id : id}
    });
    if(callFlow){
      let callFlowMenus = await TwilioCallFlowMenu.findAll({
        where : { 
          status : 1,
          twilio_call_flow_id : id
        },
        order: [['id', 'ASC']]
      })
      const data = {
        ...callFlow.toJSON(),
        call_flow_menus: callFlowMenus.map(menu => menu.toJSON()),
      };
      return data;
    }else{
      return false;
    }
  }
  catch(error){
    console.log(error);
  }
}

const updateCallFlow = async (id,data) => {
  try{
    let result = await TwilioCallFlows.update(data,{
      where : { id : id}
    })
    console.log("updateCallFlow -- ",result);
    return result ? true : false;
  }
  catch(error){
    console.log("Error",error);
  }
}

const deactivateOtherCallFlow = async () => {
  try{
    let data = {};
    data['status'] = 0;
    let result = await TwilioCallFlows.update(data,{
      where : { status : 1}
    })
    return result ? true : false;
  }
  catch(error){
    console.log("Error",error);
  }
}

const addCallFlowMenu = async (data) => {
  try{
    let result = await TwilioCallFlowMenu.create(data);
    return result.id;
  }
  catch(error){
    console.log("Error",error);
  }
}

const deleteCallFlowMenu = async (id) => {
  try{
    let result = await TwilioCallFlowMenu.destroy({
      where : {twilio_call_flow_id : id}
    });
    return result;
  }
  catch(error){
    console.log("Error",error);
  }
}

const updateCallSetting = async (name,data) => {
  const result = await TwilioCallSettings.update(data,{
    where : { name : name}
  });
  return result ? true : false;
}

const updateTwilioConferences = async (conferenceSid,data) => {
  const result = await TwilioConference.update(data,{
    where : { sid : conferenceSid}
  })
		return result ? true : false;
}

const addTwilioSms = async (data) => {
  const result = await TwilioSms.create(data);
  return result ? true : false;
}

module.exports = {
  TwilioSms,
  getActiveCallFlow,
  addCallRecording,
  updateCallRecording,
  addTwilioCalls,
  getAllCallLogs,
  getAllSmsList,
  getCallSettings,
  updateCallSettings,
  getAllRecordings,
  getTotalCalls,
  totalMissedCalls,
  getTotalTalkTime,
  secondsToTime,
  getAllDepartments,
  getAgentsByDepartment,
  getAllCallFlows,
  addCallFlow,
  deactivateOtherCallFlow,
  updateCallFlow,
  addCallFlowMenu,
  deleteCallFlowMenu,
  updateCallSetting,
  getCallFlowById,
  updateTwilioConferences,
  addTwilioSms,
  getForwardNumberOfAvailableWorker
};
