
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class User_invitationsDBApi {
    

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

        const user_invitations = await db.user_invitations.create(
            {
                id: data.id || undefined,
        
        invitee_email: data.invitee_email
        ||
        null
            ,
            
        invitee_name: data.invitee_name
        ||
        null
            ,
            
        role: data.role
        ||
        null
            ,
            
        invite_token_hash: data.invite_token_hash
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
        revoked_at: data.revoked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_invitations.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await user_invitations.setInvited_by_user( data.invited_by_user || null, {
            transaction,
        });
        

        

        

        return user_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 user_invitationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invitee_email: item.invitee_email
            ||
            null
            ,
            
                invitee_name: item.invitee_name
            ||
            null
            ,
            
                role: item.role
            ||
            null
            ,
            
                invite_token_hash: item.invite_token_hash
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                accepted_at: item.accepted_at
            ||
            null
            ,
            
                revoked_at: item.revoked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_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 user_invitations = await TenantAccess.findByPkOrThrow(db.user_invitations, id, options);


        

        const updatePayload = {};
        
        if (data.invitee_email !== undefined) updatePayload.invitee_email = data.invitee_email;
        
        
        if (data.invitee_name !== undefined) updatePayload.invitee_name = data.invitee_name;
        
        
        if (data.role !== undefined) updatePayload.role = data.role;
        
        
        if (data.invite_token_hash !== undefined) updatePayload.invite_token_hash = data.invite_token_hash;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
        
        
        if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await user_invitations.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.invited_by_user !== undefined) {
            await user_invitations.setInvited_by_user(
              
              data.invited_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return user_invitations;
    }

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

        const user_invitations = await TenantAccess.findAllByIds(db.user_invitations, ids, options);

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


        return user_invitations;
    }

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

        const user_invitations = await TenantAccess.findByPkOrThrow(db.user_invitations, id, options);

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

        await user_invitations.destroy({
            transaction
        });

        return user_invitations;
    }

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

        const user_invitations = await TenantAccess.findOne(db.user_invitations, where, options);

        if (!user_invitations) {
            return user_invitations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await user_invitations.getOrganization({
            transaction
        });
        
        
        output.invited_by_user = await user_invitations.getInvited_by_user({
            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: 'organization',
        
      },

      {
        model: db.users,
        as: 'invited_by_user',
        
        where: filter.invited_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.invited_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.invited_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.invitee_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_invitations',
                        'invitee_email',
                        filter.invitee_email,
                    ),
                };
            }
            
            if (filter.invitee_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_invitations',
                        'invitee_name',
                        filter.invitee_name,
                    ),
                };
            }
            
            if (filter.invite_token_hash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_invitations',
                        'invite_token_hash',
                        filter.invite_token_hash,
                    ),
                };
            }
            

            
            

            
            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.revoked_atRange) {
                const [start, end] = filter.revoked_atRange;

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

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

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

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.user_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(
                        'user_invitations',
                        'invitee_email',
                        query,
                    ),
                ],
            };
        }

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

    
};

