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

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

        const community_comments = await db.community_comments.create(
            {
                id: data.id || undefined,
        
        body: data.body
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        like_count: data.like_count
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await community_comments.setPost( data.post || null, {
            transaction,
        });
        
        await community_comments.setAuthor( data.author || null, {
            transaction,
        });
        
        await community_comments.setParent_comment( data.parent_comment || null, {
            transaction,
        });
        

        

        

        return community_comments;
    }
    

    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 community_commentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                body: item.body
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                like_count: item.like_count
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return community_comments;
    }

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

        const community_comments = await db.community_comments.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.post !== undefined) {
            await community_comments.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await community_comments.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        
        if (data.parent_comment !== undefined) {
            await community_comments.setParent_comment(
              
              data.parent_comment,
              
              { transaction }
            );
        }
        

        
        

        

        return community_comments;
    }

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

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

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


        return community_comments;
    }

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

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

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

        await community_comments.destroy({
            transaction
        });

        return community_comments;
    }

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

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

        if (!community_comments) {
            return community_comments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.community_reactions_comment = await community_comments.getCommunity_reactions_comment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.post = await community_comments.getPost({
            transaction
        });
        
        
        output.author = await community_comments.getAuthor({
            transaction
        });
        
        
        output.parent_comment = await community_comments.getParent_comment({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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



    ];

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

            
            if (filter.body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_comments',
                        'body',
                        filter.body,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.community_comments.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'community_comments',
                        'body',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

