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

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

        const post_comments = await db.post_comments.create(
            {
                id: data.id || undefined,
        
        body: data.body
        ||
        null
            ,
            
        is_pinned: data.is_pinned
        ||
        false
        
            ,
            
        commented_at: data.commented_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return post_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 post_commentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                body: item.body
            ||
            null
            ,
            
                is_pinned: item.is_pinned
            ||
            false
        
            ,
            
                commented_at: item.commented_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return post_comments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.body !== undefined) updatePayload.body = data.body;
        
        
        if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
        
        
        if (data.commented_at !== undefined) updatePayload.commented_at = data.commented_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return post_comments;
    }

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

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

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


        return post_comments;
    }

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

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

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

        await post_comments.destroy({
            transaction
        });

        return post_comments;
    }

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

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

        if (!post_comments) {
            return post_comments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.post = await post_comments.getPost({
            transaction
        });
        
        
        output.author = await post_comments.getAuthor({
            transaction
        });
        
        
        output.parent_comment = await post_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.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: '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.post_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(
                        'post_comments',
                        'body',
                        filter.body,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      



            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.post_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(
                        'post_comments',
                        'body',
                        query,
                    ),
                ],
            };
        }

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

    
};

