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

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

        const room_invitations = await db.room_invitations.create(
            {
                id: data.id || undefined,
        
        invitee_email: data.invitee_email
        ||
        null
            ,
            
        invite_code: data.invite_code
        ||
        null
            ,
            
        invite_role: data.invite_role
        ||
        null
            ,
            
        invitation_status: data.invitation_status
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return room_invitations;
    }
    

    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 room_invitationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invitee_email: item.invitee_email
            ||
            null
            ,
            
                invite_code: item.invite_code
            ||
            null
            ,
            
                invite_role: item.invite_role
            ||
            null
            ,
            
                invitation_status: item.invitation_status
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                accepted_at: item.accepted_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return room_invitations;
    }

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


        

        const updatePayload = {};
        
        if (data.invitee_email !== undefined) updatePayload.invitee_email = data.invitee_email;
        
        
        if (data.invite_code !== undefined) updatePayload.invite_code = data.invite_code;
        
        
        if (data.invite_role !== undefined) updatePayload.invite_role = data.invite_role;
        
        
        if (data.invitation_status !== undefined) updatePayload.invitation_status = data.invitation_status;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return room_invitations;
    }

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

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

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


        return room_invitations;
    }

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

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

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

        await room_invitations.destroy({
            transaction
        });

        return room_invitations;
    }

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

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

        if (!room_invitations) {
            return room_invitations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.room = await room_invitations.getRoom({
            transaction
        });
        
        
        output.invited_by = await room_invitations.getInvited_by({
            transaction
        });
        
        
        output.organizations = await room_invitations.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.users,
        as: 'invited_by',
        
        where: filter.invited_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.invited_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.invited_by.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.invitee_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'room_invitations',
                        'invitee_email',
                        filter.invitee_email,
                    ),
                };
            }
            
            if (filter.invite_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'room_invitations',
                        'invite_code',
                        filter.invite_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.invite_role) {
                where = {
                    ...where,
                invite_role: filter.invite_role,
            };
            }
            
            if (filter.invitation_status) {
                where = {
                    ...where,
                invitation_status: filter.invitation_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.room_invitations.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(
                        'room_invitations',
                        'invitee_email',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

