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

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

        const voice_sessions = await db.voice_sessions.create(
            {
                id: data.id || undefined,
        
        state: data.state
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        stt_provider: data.stt_provider
        ||
        null
            ,
            
        tts_provider: data.tts_provider
        ||
        null
            ,
            
        detected_language: data.detected_language
        ||
        null
            ,
            
        last_error: data.last_error
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await voice_sessions.setConversation( data.conversation || null, {
            transaction,
        });
        
        await voice_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.voice_sessions.getTableName(),
                belongsToColumn: 'audio_recordings',
                belongsToId: voice_sessions.id,
            },
            data.audio_recordings,
            options,
        );
        

        return voice_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_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                state: item.state
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                stt_provider: item.stt_provider
            ||
            null
            ,
            
                tts_provider: item.tts_provider
            ||
            null
            ,
            
                detected_language: item.detected_language
            ||
            null
            ,
            
                last_error: item.last_error
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < voice_sessions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.voice_sessions.getTableName(),
                    belongsToColumn: 'audio_recordings',
                    belongsToId: voice_sessions[i].id,
                },
                data[i].audio_recordings,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.stt_provider !== undefined) updatePayload.stt_provider = data.stt_provider;
        
        
        if (data.tts_provider !== undefined) updatePayload.tts_provider = data.tts_provider;
        
        
        if (data.detected_language !== undefined) updatePayload.detected_language = data.detected_language;
        
        
        if (data.last_error !== undefined) updatePayload.last_error = data.last_error;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.conversation !== undefined) {
            await voice_sessions.setConversation(
              
              data.conversation,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await voice_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.voice_sessions.getTableName(),
                belongsToColumn: 'audio_recordings',
                belongsToId: voice_sessions.id,
            },
            data.audio_recordings,
            options,
        );
        

        return voice_sessions;
    }

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

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

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


        return voice_sessions;
    }

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

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

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

        await voice_sessions.destroy({
            transaction
        });

        return voice_sessions;
    }

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

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

        if (!voice_sessions) {
            return voice_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        output.messages_voice_session = await voice_sessions.getMessages_voice_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conversation = await voice_sessions.getConversation({
            transaction
        });
        
        
        output.audio_recordings = await voice_sessions.getAudio_recordings({
            transaction
        });
        
        
        output.organizations = await voice_sessions.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.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.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'audio_recordings',
      },

    ];

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

            
            if (filter.stt_provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_sessions',
                        'stt_provider',
                        filter.stt_provider,
                    ),
                };
            }
            
            if (filter.tts_provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_sessions',
                        'tts_provider',
                        filter.tts_provider,
                    ),
                };
            }
            
            if (filter.detected_language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_sessions',
                        'detected_language',
                        filter.detected_language,
                    ),
                };
            }
            
            if (filter.last_error) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'voice_sessions',
                        'last_error',
                        filter.last_error,
                    ),
                };
            }
            

            
            
            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.state) {
                where = {
                    ...where,
                state: filter.state,
            };
            }
            


      

      
      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.voice_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_sessions',
                        'stt_provider',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

