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

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

        const community_posts = await db.community_posts.create(
            {
                id: data.id || undefined,
        
        post_type: data.post_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        body: data.body
        ||
        null
            ,
            
        image_url: data.image_url
        ||
        null
            ,
            
        resource_url: data.resource_url
        ||
        null
            ,
            
        poll_options_json: data.poll_options_json
        ||
        null
            ,
            
        is_pinned: data.is_pinned
        ||
        false
        
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        like_count: data.like_count
        ||
        null
            ,
            
        love_count: data.love_count
        ||
        null
            ,
            
        insightful_count: data.insightful_count
        ||
        null
            ,
            
        comment_count: data.comment_count
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await community_posts.setSpace( data.space || null, {
            transaction,
        });
        
        await community_posts.setAuthor( data.author || null, {
            transaction,
        });
        

        

        

        return community_posts;
    }
    

    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_postsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                post_type: item.post_type
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                body: item.body
            ||
            null
            ,
            
                image_url: item.image_url
            ||
            null
            ,
            
                resource_url: item.resource_url
            ||
            null
            ,
            
                poll_options_json: item.poll_options_json
            ||
            null
            ,
            
                is_pinned: item.is_pinned
            ||
            false
        
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                like_count: item.like_count
            ||
            null
            ,
            
                love_count: item.love_count
            ||
            null
            ,
            
                insightful_count: item.insightful_count
            ||
            null
            ,
            
                comment_count: item.comment_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_posts = await db.community_posts.bulkCreate(community_postsData, { transaction });

        // For each item created, replace relation files
        

        return community_posts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.image_url !== undefined) updatePayload.image_url = data.image_url;
        
        
        if (data.resource_url !== undefined) updatePayload.resource_url = data.resource_url;
        
        
        if (data.poll_options_json !== undefined) updatePayload.poll_options_json = data.poll_options_json;
        
        
        if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
        
        
        if (data.love_count !== undefined) updatePayload.love_count = data.love_count;
        
        
        if (data.insightful_count !== undefined) updatePayload.insightful_count = data.insightful_count;
        
        
        if (data.comment_count !== undefined) updatePayload.comment_count = data.comment_count;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.space !== undefined) {
            await community_posts.setSpace(
              
              data.space,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await community_posts.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        

        
        

        

        return community_posts;
    }

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

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

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


        return community_posts;
    }

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

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

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

        await community_posts.destroy({
            transaction
        });

        return community_posts;
    }

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

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

        if (!community_posts) {
            return community_posts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.community_comments_post = await community_posts.getCommunity_comments_post({
            transaction
        });
        
        
        output.community_reactions_post = await community_posts.getCommunity_reactions_post({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.space = await community_posts.getSpace({
            transaction
        });
        
        
        output.author = await community_posts.getAuthor({
            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.spaces,
        as: 'space',
        
        where: filter.space ? {
          [Op.or]: [
            { id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.space.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_posts',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_posts',
                        'body',
                        filter.body,
                    ),
                };
            }
            
            if (filter.image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_posts',
                        'image_url',
                        filter.image_url,
                    ),
                };
            }
            
            if (filter.resource_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_posts',
                        'resource_url',
                        filter.resource_url,
                    ),
                };
            }
            
            if (filter.poll_options_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'community_posts',
                        'poll_options_json',
                        filter.poll_options_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    comment_count: {
                    ...where.comment_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.post_type) {
                where = {
                    ...where,
                post_type: filter.post_type,
            };
            }
            
            if (filter.is_pinned) {
                where = {
                    ...where,
                is_pinned: filter.is_pinned,
            };
            }
            
            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_posts.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_posts',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

