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

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

        const conference_nodes = await db.conference_nodes.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        node_type: data.node_type
        ||
        null
            ,
            
        region: data.region
        ||
        null
            ,
            
        zone: data.zone
        ||
        null
            ,
            
        endpoint: data.endpoint
        ||
        null
            ,
            
        health_status: data.health_status
        ||
        null
            ,
            
        last_heartbeat_at: data.last_heartbeat_at
        ||
        null
            ,
            
        cpu_utilization: data.cpu_utilization
        ||
        null
            ,
            
        memory_utilization: data.memory_utilization
        ||
        null
            ,
            
        current_conferences: data.current_conferences
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await conference_nodes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return conference_nodes;
    }
    

    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 conference_nodesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                node_type: item.node_type
            ||
            null
            ,
            
                region: item.region
            ||
            null
            ,
            
                zone: item.zone
            ||
            null
            ,
            
                endpoint: item.endpoint
            ||
            null
            ,
            
                health_status: item.health_status
            ||
            null
            ,
            
                last_heartbeat_at: item.last_heartbeat_at
            ||
            null
            ,
            
                cpu_utilization: item.cpu_utilization
            ||
            null
            ,
            
                memory_utilization: item.memory_utilization
            ||
            null
            ,
            
                current_conferences: item.current_conferences
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return conference_nodes;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.node_type !== undefined) updatePayload.node_type = data.node_type;
        
        
        if (data.region !== undefined) updatePayload.region = data.region;
        
        
        if (data.zone !== undefined) updatePayload.zone = data.zone;
        
        
        if (data.endpoint !== undefined) updatePayload.endpoint = data.endpoint;
        
        
        if (data.health_status !== undefined) updatePayload.health_status = data.health_status;
        
        
        if (data.last_heartbeat_at !== undefined) updatePayload.last_heartbeat_at = data.last_heartbeat_at;
        
        
        if (data.cpu_utilization !== undefined) updatePayload.cpu_utilization = data.cpu_utilization;
        
        
        if (data.memory_utilization !== undefined) updatePayload.memory_utilization = data.memory_utilization;
        
        
        if (data.current_conferences !== undefined) updatePayload.current_conferences = data.current_conferences;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return conference_nodes;
    }

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

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

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


        return conference_nodes;
    }

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

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

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

        await conference_nodes.destroy({
            transaction
        });

        return conference_nodes;
    }

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

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

        if (!conference_nodes) {
            return conference_nodes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sfu_allocations_conference_node = await conference_nodes.getSfu_allocations_conference_node({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await conference_nodes.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'conference_nodes',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.zone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'conference_nodes',
                        'zone',
                        filter.zone,
                    ),
                };
            }
            
            if (filter.endpoint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'conference_nodes',
                        'endpoint',
                        filter.endpoint,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.node_type) {
                where = {
                    ...where,
                node_type: filter.node_type,
            };
            }
            
            if (filter.region) {
                where = {
                    ...where,
                region: filter.region,
            };
            }
            
            if (filter.health_status) {
                where = {
                    ...where,
                health_status: filter.health_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.conference_nodes.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(
                        'conference_nodes',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

