
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class CallsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const calls = await db.calls.create(
            {
                id: data.id || undefined,
        
        call_type: data.call_type
        ||
        null
            ,
            
        call_status: data.call_status
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await calls.setConversation( data.conversation || null, {
            transaction,
        });
        
        await calls.setInitiator( data.initiator || null, {
            transaction,
        });
        

        

        

        return calls;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const callsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                call_type: item.call_type
            ||
            null
            ,
            
                call_status: item.call_status
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const calls = await db.calls.bulkCreate(callsData, { transaction });

        // For each item created, replace relation files
        

        return calls;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const calls = await db.calls.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.call_type !== undefined) updatePayload.call_type = data.call_type;
        
        
        if (data.call_status !== undefined) updatePayload.call_status = data.call_status;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        updatePayload.updatedById = currentUser.id;

        await calls.update(updatePayload, {transaction});

        
        
        if (data.conversation !== undefined) {
            await calls.setConversation(
              
              data.conversation,
              
              { transaction }
            );
        }
        
        if (data.initiator !== undefined) {
            await calls.setInitiator(
              
              data.initiator,
              
              { transaction }
            );
        }
        

        
        

        

        return calls;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const calls = await db.calls.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of calls) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of calls) {
                await record.destroy({transaction});
            }
        });


        return calls;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const calls = await db.calls.findByPk(id, options);

        await calls.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await calls.destroy({
            transaction
        });

        return calls;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const calls = await db.calls.findOne(
            { where },
            { transaction },
        );

        if (!calls) {
            return calls;
        }

        const output = calls.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conversation = await calls.getConversation({
            transaction
        });
        
        
        output.initiator = await calls.getInitiator({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.conversations,
        as: 'conversation',
        
        where: filter.conversation ? {
          [Op.or]: [
            { id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'initiator',
        
        where: filter.initiator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.initiator.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.initiator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            started_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    ended_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            if (filter.started_atRange) {
                const [start, end] = filter.started_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    started_at: {
                    ...where.started_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    started_at: {
                    ...where.started_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.ended_atRange) {
                const [start, end] = filter.ended_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    ended_at: {
                    ...where.ended_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    ended_at: {
                    ...where.ended_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.call_type) {
                where = {
                    ...where,
                call_type: filter.call_type,
            };
            }
            
            if (filter.call_status) {
                where = {
                    ...where,
                call_status: filter.call_status,
            };
            }
            


      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.calls.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'calls',
                        'call_status',
                        query,
                    ),
                ],
            };
        }

        const records = await db.calls.findAll({
            attributes: [ 'id', 'call_status' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['call_status', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.call_status,
        }));
    }

    
};

