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

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

        const quality_reports = await db.quality_reports.create(
            {
                id: data.id || undefined,
        
        reported_at: data.reported_at
        ||
        null
            ,
            
        packet_loss_percent: data.packet_loss_percent
        ||
        null
            ,
            
        rtt_ms: data.rtt_ms
        ||
        null
            ,
            
        jitter_ms: data.jitter_ms
        ||
        null
            ,
            
        send_bitrate_kbps: data.send_bitrate_kbps
        ||
        null
            ,
            
        recv_bitrate_kbps: data.recv_bitrate_kbps
        ||
        null
            ,
            
        media_quality: data.media_quality
        ||
        null
            ,
            
        raw_stats: data.raw_stats
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quality_reports.setConference( data.conference || null, {
            transaction,
        });
        
        await quality_reports.setParticipant( data.participant || null, {
            transaction,
        });
        
        await quality_reports.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return quality_reports;
    }
    

    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 quality_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reported_at: item.reported_at
            ||
            null
            ,
            
                packet_loss_percent: item.packet_loss_percent
            ||
            null
            ,
            
                rtt_ms: item.rtt_ms
            ||
            null
            ,
            
                jitter_ms: item.jitter_ms
            ||
            null
            ,
            
                send_bitrate_kbps: item.send_bitrate_kbps
            ||
            null
            ,
            
                recv_bitrate_kbps: item.recv_bitrate_kbps
            ||
            null
            ,
            
                media_quality: item.media_quality
            ||
            null
            ,
            
                raw_stats: item.raw_stats
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return quality_reports;
    }

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


        

        const updatePayload = {};
        
        if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
        
        
        if (data.packet_loss_percent !== undefined) updatePayload.packet_loss_percent = data.packet_loss_percent;
        
        
        if (data.rtt_ms !== undefined) updatePayload.rtt_ms = data.rtt_ms;
        
        
        if (data.jitter_ms !== undefined) updatePayload.jitter_ms = data.jitter_ms;
        
        
        if (data.send_bitrate_kbps !== undefined) updatePayload.send_bitrate_kbps = data.send_bitrate_kbps;
        
        
        if (data.recv_bitrate_kbps !== undefined) updatePayload.recv_bitrate_kbps = data.recv_bitrate_kbps;
        
        
        if (data.media_quality !== undefined) updatePayload.media_quality = data.media_quality;
        
        
        if (data.raw_stats !== undefined) updatePayload.raw_stats = data.raw_stats;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.conference !== undefined) {
            await quality_reports.setConference(
              
              data.conference,
              
              { transaction }
            );
        }
        
        if (data.participant !== undefined) {
            await quality_reports.setParticipant(
              
              data.participant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await quality_reports.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return quality_reports;
    }

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

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

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


        return quality_reports;
    }

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

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

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

        await quality_reports.destroy({
            transaction
        });

        return quality_reports;
    }

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

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

        if (!quality_reports) {
            return quality_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conference = await quality_reports.getConference({
            transaction
        });
        
        
        output.participant = await quality_reports.getParticipant({
            transaction
        });
        
        
        output.organizations = await quality_reports.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.conferences,
        as: 'conference',
        
        where: filter.conference ? {
          [Op.or]: [
            { id: { [Op.in]: filter.conference.split('|').map(term => Utils.uuid(term)) } },
            {
              conference_key: {
                [Op.or]: filter.conference.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.participants,
        as: 'participant',
        
        where: filter.participant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.participant.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.participant.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.raw_stats) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_reports',
                        'raw_stats',
                        filter.raw_stats,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

