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

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

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

        
        await reel_comments.setReel( data.reel || null, {
            transaction,
        });
        
        await reel_comments.setAuthor( data.author || null, {
            transaction,
        });
        
        await reel_comments.setParent_comment( data.parent_comment || null, {
            transaction,
        });
        

        

        

        return reel_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 reel_commentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                body: item.body
            ||
            null
            ,
            
                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 reel_comments = await db.reel_comments.bulkCreate(reel_commentsData, { transaction });

        // For each item created, replace relation files
        

        return reel_comments;
    }

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

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


        

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

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

        
        
        if (data.reel !== undefined) {
            await reel_comments.setReel(
              
              data.reel,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await reel_comments.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        
        if (data.parent_comment !== undefined) {
            await reel_comments.setParent_comment(
              
              data.parent_comment,
              
              { transaction }
            );
        }
        

        
        

        

        return reel_comments;
    }

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

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

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


        return reel_comments;
    }

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

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

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

        await reel_comments.destroy({
            transaction
        });

        return reel_comments;
    }

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

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

        if (!reel_comments) {
            return reel_comments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reel = await reel_comments.getReel({
            transaction
        });
        
        
        output.author = await reel_comments.getAuthor({
            transaction
        });
        
        
        output.parent_comment = await reel_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.reels,
        as: 'reel',
        
        where: filter.reel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reel.split('|').map(term => Utils.uuid(term)) } },
            {
              caption: {
                [Op.or]: filter.reel.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.reel_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(
                        'reel_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.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.reel_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(
                        'reel_comments',
                        'body',
                        query,
                    ),
                ],
            };
        }

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

    
};

