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

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

        const content_moderation_items = await db.content_moderation_items.create(
            {
                id: data.id || undefined,
        
        content_type: data.content_type
        ||
        null
            ,
            
        text_excerpt: data.text_excerpt
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        queued_at: data.queued_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        moderation_notes: data.moderation_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await content_moderation_items.setUser( data.user || null, {
            transaction,
        });
        
        await content_moderation_items.setMessage( data.message || null, {
            transaction,
        });
        
        await content_moderation_items.setPhoto( data.photo || null, {
            transaction,
        });
        
        await content_moderation_items.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        

        

        

        return content_moderation_items;
    }
    

    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 content_moderation_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                content_type: item.content_type
            ||
            null
            ,
            
                text_excerpt: item.text_excerpt
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                queued_at: item.queued_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                moderation_notes: item.moderation_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return content_moderation_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.text_excerpt !== undefined) updatePayload.text_excerpt = data.text_excerpt;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.queued_at !== undefined) updatePayload.queued_at = data.queued_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.moderation_notes !== undefined) updatePayload.moderation_notes = data.moderation_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await content_moderation_items.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.message !== undefined) {
            await content_moderation_items.setMessage(
              
              data.message,
              
              { transaction }
            );
        }
        
        if (data.photo !== undefined) {
            await content_moderation_items.setPhoto(
              
              data.photo,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by !== undefined) {
            await content_moderation_items.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        

        
        

        

        return content_moderation_items;
    }

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

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

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


        return content_moderation_items;
    }

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

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

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

        await content_moderation_items.destroy({
            transaction
        });

        return content_moderation_items;
    }

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

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

        if (!content_moderation_items) {
            return content_moderation_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await content_moderation_items.getUser({
            transaction
        });
        
        
        output.message = await content_moderation_items.getMessage({
            transaction
        });
        
        
        output.photo = await content_moderation_items.getPhoto({
            transaction
        });
        
        
        output.reviewed_by = await content_moderation_items.getReviewed_by({
            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.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.messages,
        as: 'message',
        
        where: filter.message ? {
          [Op.or]: [
            { id: { [Op.in]: filter.message.split('|').map(term => Utils.uuid(term)) } },
            {
              body: {
                [Op.or]: filter.message.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.text_excerpt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_moderation_items',
                        'text_excerpt',
                        filter.text_excerpt,
                    ),
                };
            }
            
            if (filter.moderation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'content_moderation_items',
                        'moderation_notes',
                        filter.moderation_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      

      



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

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

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

    
};

