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

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

        const moderation_reports = await db.moderation_reports.create(
            {
                id: data.id || undefined,
        
        target_type: data.target_type
        ||
        null
            ,
            
        reason: data.reason
        ||
        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 moderation_reports.setReporter( data.reporter || null, {
            transaction,
        });
        

        

        

        return 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 moderation_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                target_type: item.target_type
            ||
            null
            ,
            
                reason: item.reason
            ||
            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 moderation_reports = await db.moderation_reports.bulkCreate(moderation_reportsData, { transaction });

        // For each item created, replace relation files
        

        return moderation_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.target_type !== undefined) updatePayload.target_type = data.target_type;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        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 moderation_reports.update(updatePayload, {transaction});

        
        
        if (data.reporter !== undefined) {
            await moderation_reports.setReporter(
              
              data.reporter,
              
              { transaction }
            );
        }
        

        
        

        

        return moderation_reports;
    }

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

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

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


        return moderation_reports;
    }

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

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

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

        await moderation_reports.destroy({
            transaction
        });

        return moderation_reports;
    }

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

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

        if (!moderation_reports) {
            return moderation_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reporter = await moderation_reports.getReporter({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

    
};

