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

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

        const conferences = await db.conferences.create(
            {
                id: data.id || undefined,
        
        conference_key: data.conference_key
        ||
        null
            ,
            
        conference_type: data.conference_type
        ||
        null
            ,
            
        conference_status: data.conference_status
        ||
        null
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        scheduled_end_at: data.scheduled_end_at
        ||
        null
            ,
            
        actual_start_at: data.actual_start_at
        ||
        null
            ,
            
        actual_end_at: data.actual_end_at
        ||
        null
            ,
            
        e2ee_enabled: data.e2ee_enabled
        ||
        false
        
            ,
            
        participant_limit: data.participant_limit
        ||
        null
            ,
            
        region_preference: data.region_preference
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await conferences.setRoom( data.room || null, {
            transaction,
        });
        
        await conferences.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return conferences;
    }
    

    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 conferencesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                conference_key: item.conference_key
            ||
            null
            ,
            
                conference_type: item.conference_type
            ||
            null
            ,
            
                conference_status: item.conference_status
            ||
            null
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                scheduled_end_at: item.scheduled_end_at
            ||
            null
            ,
            
                actual_start_at: item.actual_start_at
            ||
            null
            ,
            
                actual_end_at: item.actual_end_at
            ||
            null
            ,
            
                e2ee_enabled: item.e2ee_enabled
            ||
            false
        
            ,
            
                participant_limit: item.participant_limit
            ||
            null
            ,
            
                region_preference: item.region_preference
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return conferences;
    }

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


        

        const updatePayload = {};
        
        if (data.conference_key !== undefined) updatePayload.conference_key = data.conference_key;
        
        
        if (data.conference_type !== undefined) updatePayload.conference_type = data.conference_type;
        
        
        if (data.conference_status !== undefined) updatePayload.conference_status = data.conference_status;
        
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
        
        
        if (data.scheduled_end_at !== undefined) updatePayload.scheduled_end_at = data.scheduled_end_at;
        
        
        if (data.actual_start_at !== undefined) updatePayload.actual_start_at = data.actual_start_at;
        
        
        if (data.actual_end_at !== undefined) updatePayload.actual_end_at = data.actual_end_at;
        
        
        if (data.e2ee_enabled !== undefined) updatePayload.e2ee_enabled = data.e2ee_enabled;
        
        
        if (data.participant_limit !== undefined) updatePayload.participant_limit = data.participant_limit;
        
        
        if (data.region_preference !== undefined) updatePayload.region_preference = data.region_preference;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return conferences;
    }

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

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

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


        return conferences;
    }

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

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

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

        await conferences.destroy({
            transaction
        });

        return conferences;
    }

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

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

        if (!conferences) {
            return conferences;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.participants_conference = await conferences.getParticipants_conference({
            transaction
        });
        
        
        
        output.sfu_allocations_conference = await conferences.getSfu_allocations_conference({
            transaction
        });
        
        
        output.breakout_rooms_conference = await conferences.getBreakout_rooms_conference({
            transaction
        });
        
        
        output.chat_channels_conference = await conferences.getChat_channels_conference({
            transaction
        });
        
        
        
        
        
        output.recordings_conference = await conferences.getRecordings_conference({
            transaction
        });
        
        
        output.transcripts_conference = await conferences.getTranscripts_conference({
            transaction
        });
        
        
        
        
        
        
        
        output.ai_companion_sessions_conference = await conferences.getAi_companion_sessions_conference({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quality_reports_conference = await conferences.getQuality_reports_conference({
            transaction
        });
        
        
        
        output.conference_events_conference = await conferences.getConference_events_conference({
            transaction
        });
        
        
        
        output.room = await conferences.getRoom({
            transaction
        });
        
        
        output.organizations = await conferences.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.rooms,
        as: 'room',
        
        where: filter.room ? {
          [Op.or]: [
            { id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.room.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.conference_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'conferences',
                        'conference_key',
                        filter.conference_key,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            scheduled_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    scheduled_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.conference_type) {
                where = {
                    ...where,
                conference_type: filter.conference_type,
            };
            }
            
            if (filter.conference_status) {
                where = {
                    ...where,
                conference_status: filter.conference_status,
            };
            }
            
            if (filter.e2ee_enabled) {
                where = {
                    ...where,
                e2ee_enabled: filter.e2ee_enabled,
            };
            }
            
            if (filter.region_preference) {
                where = {
                    ...where,
                region_preference: filter.region_preference,
            };
            }
            


      

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

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

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

    
};

