
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 Video_callsDBApi {
    

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

        const video_calls = await db.video_calls.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        provider_room_name: data.provider_room_name
        ||
        null
            ,
            
        provider_session_reference: data.provider_session_reference
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        call_status: data.call_status
        ||
        null
            ,
            
        call_notes: data.call_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await video_calls.setConsultation( data.consultation || null, {
            transaction,
        });
        
        await video_calls.setChat_session( data.chat_session || null, {
            transaction,
        });
        
        await video_calls.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return video_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 video_callsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                provider_room_name: item.provider_room_name
            ||
            null
            ,
            
                provider_session_reference: item.provider_session_reference
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                call_status: item.call_status
            ||
            null
            ,
            
                call_notes: item.call_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return video_calls;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.provider_room_name !== undefined) updatePayload.provider_room_name = data.provider_room_name;
        
        
        if (data.provider_session_reference !== undefined) updatePayload.provider_session_reference = data.provider_session_reference;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.call_status !== undefined) updatePayload.call_status = data.call_status;
        
        
        if (data.call_notes !== undefined) updatePayload.call_notes = data.call_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.consultation !== undefined) {
            await video_calls.setConsultation(
              
              data.consultation,
              
              { transaction }
            );
        }
        
        if (data.chat_session !== undefined) {
            await video_calls.setChat_session(
              
              data.chat_session,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await video_calls.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return video_calls;
    }

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

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

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


        return video_calls;
    }

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

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

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

        await video_calls.destroy({
            transaction
        });

        return video_calls;
    }

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

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

        if (!video_calls) {
            return video_calls;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.consultation = await video_calls.getConsultation({
            transaction
        });
        
        
        output.chat_session = await video_calls.getChat_session({
            transaction
        });
        
        
        output.organizations = await video_calls.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.provider_room_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'video_calls',
                        'provider_room_name',
                        filter.provider_room_name,
                    ),
                };
            }
            
            if (filter.provider_session_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'video_calls',
                        'provider_session_reference',
                        filter.provider_session_reference,
                    ),
                };
            }
            
            if (filter.call_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'video_calls',
                        'call_notes',
                        filter.call_notes,
                    ),
                };
            }
            

            
            

            
            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.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            if (filter.call_status) {
                where = {
                    ...where,
                call_status: filter.call_status,
            };
            }
            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.video_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

