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

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

        const voice_assistant_sessions = await db.voice_assistant_sessions.create(
            {
                id: data.id || undefined,
        
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        transcript: data.transcript
        ||
        null
            ,
            
        assistant_summary: data.assistant_summary
        ||
        null
            ,
            
        outcome: data.outcome
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await voice_assistant_sessions.setPatient( data.patient || null, {
            transaction,
        });
        
        await voice_assistant_sessions.setInitiated_by_user( data.initiated_by_user || null, {
            transaction,
        });
        
        await voice_assistant_sessions.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return voice_assistant_sessions;
    }
    

    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 voice_assistant_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                transcript: item.transcript
            ||
            null
            ,
            
                assistant_summary: item.assistant_summary
            ||
            null
            ,
            
                outcome: item.outcome
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return voice_assistant_sessions;
    }

    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 voice_assistant_sessions = await db.voice_assistant_sessions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.transcript !== undefined) updatePayload.transcript = data.transcript;
        
        
        if (data.assistant_summary !== undefined) updatePayload.assistant_summary = data.assistant_summary;
        
        
        if (data.outcome !== undefined) updatePayload.outcome = data.outcome;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await voice_assistant_sessions.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.initiated_by_user !== undefined) {
            await voice_assistant_sessions.setInitiated_by_user(
              
              data.initiated_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await voice_assistant_sessions.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return voice_assistant_sessions;
    }

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

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

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


        return voice_assistant_sessions;
    }

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

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

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

        await voice_assistant_sessions.destroy({
            transaction
        });

        return voice_assistant_sessions;
    }

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

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

        if (!voice_assistant_sessions) {
            return voice_assistant_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await voice_assistant_sessions.getPatient({
            transaction
        });
        
        
        output.initiated_by_user = await voice_assistant_sessions.getInitiated_by_user({
            transaction
        });
        
        
        output.accounts = await voice_assistant_sessions.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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



    ];

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

            
            if (filter.transcript) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_assistant_sessions',
                        'transcript',
                        filter.transcript,
                    ),
                };
            }
            
            if (filter.assistant_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_assistant_sessions',
                        'assistant_summary',
                        filter.assistant_summary,
                    ),
                };
            }
            

            
            

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


      

      

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

        where = {
          ...where,
          accountsId: {[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.accountsId;
        }
        

        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.voice_assistant_sessions.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(
                        'voice_assistant_sessions',
                        'outcome',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

