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

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

        const post_engagements = await db.post_engagements.create(
            {
                id: data.id || undefined,
        
        engagement_type: data.engagement_type
        ||
        null
            ,
            
        comment_text: data.comment_text
        ||
        null
            ,
            
        engaged_at: data.engaged_at
        ||
        null
            ,
            
        is_reward_eligible: data.is_reward_eligible
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await post_engagements.setPost( data.post || null, {
            transaction,
        });
        
        await post_engagements.setUser( data.user || null, {
            transaction,
        });
        
        await post_engagements.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return post_engagements;
    }
    

    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 post_engagementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                engagement_type: item.engagement_type
            ||
            null
            ,
            
                comment_text: item.comment_text
            ||
            null
            ,
            
                engaged_at: item.engaged_at
            ||
            null
            ,
            
                is_reward_eligible: item.is_reward_eligible
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return post_engagements;
    }

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


        

        const updatePayload = {};
        
        if (data.engagement_type !== undefined) updatePayload.engagement_type = data.engagement_type;
        
        
        if (data.comment_text !== undefined) updatePayload.comment_text = data.comment_text;
        
        
        if (data.engaged_at !== undefined) updatePayload.engaged_at = data.engaged_at;
        
        
        if (data.is_reward_eligible !== undefined) updatePayload.is_reward_eligible = data.is_reward_eligible;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.post !== undefined) {
            await post_engagements.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await post_engagements.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await post_engagements.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return post_engagements;
    }

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

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

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


        return post_engagements;
    }

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

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

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

        await post_engagements.destroy({
            transaction
        });

        return post_engagements;
    }

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

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

        if (!post_engagements) {
            return post_engagements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.post = await post_engagements.getPost({
            transaction
        });
        
        
        output.user = await post_engagements.getUser({
            transaction
        });
        
        
        output.organizations = await post_engagements.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.posts,
        as: 'post',
        
        where: filter.post ? {
          [Op.or]: [
            { id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
            {
              caption: {
                [Op.or]: filter.post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.comment_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'post_engagements',
                        'comment_text',
                        filter.comment_text,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.engagement_type) {
                where = {
                    ...where,
                engagement_type: filter.engagement_type,
            };
            }
            
            if (filter.is_reward_eligible) {
                where = {
                    ...where,
                is_reward_eligible: filter.is_reward_eligible,
            };
            }
            


      

      

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

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

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

    
};

