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

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

        const reports = await db.reports.create(
            {
                id: data.id || undefined,
        
        report_type: data.report_type
        ||
        null
            ,
            
        details: data.details
        ||
        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 reports.setPlace( data.place || null, {
            transaction,
        });
        
        await reports.setReporter( data.reporter || null, {
            transaction,
        });
        

        

        

        return 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 reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                report_type: item.report_type
            ||
            null
            ,
            
                details: item.details
            ||
            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 reports = await db.reports.bulkCreate(reportsData, { transaction });

        // For each item created, replace relation files
        

        return reports;
    }

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

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


        

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

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

        
        

        

        return reports;
    }

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

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

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


        return reports;
    }

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

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

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

        await reports.destroy({
            transaction
        });

        return reports;
    }

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

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

        if (!reports) {
            return reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.place = await reports.getPlace({
            transaction
        });
        
        
        output.reporter = await 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.places,
        as: 'place',
        
        where: filter.place ? {
          [Op.or]: [
            { id: { [Op.in]: filter.place.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.place.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reports',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            

            
            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.report_type) {
                where = {
                    ...where,
                report_type: filter.report_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.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(
                        'reports',
                        'details',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

