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

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

        const community_reports = await db.community_reports.create(
            {
                id: data.id || undefined,
        
        content_type: data.content_type
        ||
        null
            ,
            
        content_id: data.content_id
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await community_reports.setReporter( data.reporter || null, {
            transaction,
        });
        
        await community_reports.setResolved_by( data.resolved_by || null, {
            transaction,
        });
        

        

        

        return community_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 community_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                content_type: item.content_type
            ||
            null
            ,
            
                content_id: item.content_id
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                status: item.status
            ||
            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 community_reports = await db.community_reports.bulkCreate(community_reportsData, { transaction });

        // For each item created, replace relation files
        

        return community_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.content_id !== undefined) updatePayload.content_id = data.content_id;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return community_reports;
    }

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

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

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


        return community_reports;
    }

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

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

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

        await community_reports.destroy({
            transaction
        });

        return community_reports;
    }

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

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

        if (!community_reports) {
            return community_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reporter = await community_reports.getReporter({
            transaction
        });
        
        
        output.resolved_by = await community_reports.getResolved_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: '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.users,
        as: 'resolved_by',
        
        where: filter.resolved_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.resolved_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.resolved_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

            
            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.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.community_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(
                        'community_reports',
                        'reason',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

