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

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

        const breakout_rooms = await db.breakout_rooms.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        breakout_key: data.breakout_key
        ||
        null
            ,
            
        breakout_status: data.breakout_status
        ||
        null
            ,
            
        target_participants: data.target_participants
        ||
        null
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return breakout_rooms;
    }
    

    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 breakout_roomsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                breakout_key: item.breakout_key
            ||
            null
            ,
            
                breakout_status: item.breakout_status
            ||
            null
            ,
            
                target_participants: item.target_participants
            ||
            null
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return breakout_rooms;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.breakout_key !== undefined) updatePayload.breakout_key = data.breakout_key;
        
        
        if (data.breakout_status !== undefined) updatePayload.breakout_status = data.breakout_status;
        
        
        if (data.target_participants !== undefined) updatePayload.target_participants = data.target_participants;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return breakout_rooms;
    }

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

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

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


        return breakout_rooms;
    }

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

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

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

        await breakout_rooms.destroy({
            transaction
        });

        return breakout_rooms;
    }

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

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

        if (!breakout_rooms) {
            return breakout_rooms;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.conference = await breakout_rooms.getConference({
            transaction
        });
        
        
        output.organizations = await breakout_rooms.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

            
            if (filter.breakout_status) {
                where = {
                    ...where,
                breakout_status: filter.breakout_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.breakout_rooms.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(
                        'breakout_rooms',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.breakout_rooms.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,
        }));
    }

    
};

