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

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

        const content_moderation_reports = await db.content_moderation_reports.create(
            {
                id: data.id || undefined,
        
        target_type: data.target_type
        ||
        null
            ,
            
        reason_code: data.reason_code
        ||
        null
            ,
            
        details_text: data.details_text
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        reported_at: data.reported_at
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await content_moderation_reports.setReporter( data.reporter || null, {
            transaction,
        });
        
        await content_moderation_reports.setPost( data.post || null, {
            transaction,
        });
        
        await content_moderation_reports.setComment( data.comment || null, {
            transaction,
        });
        
        await content_moderation_reports.setMessage( data.message || null, {
            transaction,
        });
        
        await content_moderation_reports.setReported_user( data.reported_user || null, {
            transaction,
        });
        
        await content_moderation_reports.setLive_stream( data.live_stream || null, {
            transaction,
        });
        
        await content_moderation_reports.setAssigned_moderator( data.assigned_moderator || null, {
            transaction,
        });
        

        

        

        return content_moderation_reports;
    }
    

    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_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                target_type: item.target_type
            ||
            null
            ,
            
                reason_code: item.reason_code
            ||
            null
            ,
            
                details_text: item.details_text
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                reported_at: item.reported_at
            ||
            null
            ,
            
                resolved_at: item.resolved_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return content_moderation_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.target_type !== undefined) updatePayload.target_type = data.target_type;
        
        
        if (data.reason_code !== undefined) updatePayload.reason_code = data.reason_code;
        
        
        if (data.details_text !== undefined) updatePayload.details_text = data.details_text;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.reporter !== undefined) {
            await content_moderation_reports.setReporter(
              
              data.reporter,
              
              { transaction }
            );
        }
        
        if (data.post !== undefined) {
            await content_moderation_reports.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.comment !== undefined) {
            await content_moderation_reports.setComment(
              
              data.comment,
              
              { transaction }
            );
        }
        
        if (data.message !== undefined) {
            await content_moderation_reports.setMessage(
              
              data.message,
              
              { transaction }
            );
        }
        
        if (data.reported_user !== undefined) {
            await content_moderation_reports.setReported_user(
              
              data.reported_user,
              
              { transaction }
            );
        }
        
        if (data.live_stream !== undefined) {
            await content_moderation_reports.setLive_stream(
              
              data.live_stream,
              
              { transaction }
            );
        }
        
        if (data.assigned_moderator !== undefined) {
            await content_moderation_reports.setAssigned_moderator(
              
              data.assigned_moderator,
              
              { transaction }
            );
        }
        

        
        

        

        return content_moderation_reports;
    }

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

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

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


        return content_moderation_reports;
    }

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

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

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

        await content_moderation_reports.destroy({
            transaction
        });

        return content_moderation_reports;
    }

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

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

        if (!content_moderation_reports) {
            return content_moderation_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reporter = await content_moderation_reports.getReporter({
            transaction
        });
        
        
        output.post = await content_moderation_reports.getPost({
            transaction
        });
        
        
        output.comment = await content_moderation_reports.getComment({
            transaction
        });
        
        
        output.message = await content_moderation_reports.getMessage({
            transaction
        });
        
        
        output.reported_user = await content_moderation_reports.getReported_user({
            transaction
        });
        
        
        output.live_stream = await content_moderation_reports.getLive_stream({
            transaction
        });
        
        
        output.assigned_moderator = await content_moderation_reports.getAssigned_moderator({
            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: 'reporter',
        
        where: filter.reporter ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reporter.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reporter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.comments,
        as: 'comment',
        
        where: filter.comment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.comment.split('|').map(term => Utils.uuid(term)) } },
            {
              body: {
                [Op.or]: filter.comment.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.users,
        as: 'reported_user',
        
        where: filter.reported_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reported_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.reported_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.target_type) {
                where = {
                    ...where,
                target_type: filter.target_type,
            };
            }
            
            if (filter.reason_code) {
                where = {
                    ...where,
                reason_code: filter.reason_code,
            };
            }
            
            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_reports.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_reports',
                        'details_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

