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

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

        const report_runs = await db.report_runs.create(
            {
                id: data.id || undefined,
        
        requested_at: data.requested_at
        ||
        null
            ,
            
        output_format: data.output_format
        ||
        null
            ,
            
        filters_json: data.filters_json
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await report_runs.setReport_definition( data.report_definition || null, {
            transaction,
        });
        
        await report_runs.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.report_runs.getTableName(),
                belongsToColumn: 'output_file',
                belongsToId: report_runs.id,
            },
            data.output_file,
            options,
        );
        

        return report_runs;
    }
    

    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 report_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                requested_at: item.requested_at
            ||
            null
            ,
            
                output_format: item.output_format
            ||
            null
            ,
            
                filters_json: item.filters_json
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < report_runs.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.report_runs.getTableName(),
                    belongsToColumn: 'output_file',
                    belongsToId: report_runs[i].id,
                },
                data[i].output_file,
                options,
            );
        }
        

        return report_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.output_format !== undefined) updatePayload.output_format = data.output_format;
        
        
        if (data.filters_json !== undefined) updatePayload.filters_json = data.filters_json;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.report_definition !== undefined) {
            await report_runs.setReport_definition(
              
              data.report_definition,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await report_runs.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.report_runs.getTableName(),
                belongsToColumn: 'output_file',
                belongsToId: report_runs.id,
            },
            data.output_file,
            options,
        );
        

        return report_runs;
    }

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

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

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


        return report_runs;
    }

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

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

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

        await report_runs.destroy({
            transaction
        });

        return report_runs;
    }

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

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

        if (!report_runs) {
            return report_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.report_definition = await report_runs.getReport_definition({
            transaction
        });
        
        
        output.requested_by_user = await report_runs.getRequested_by_user({
            transaction
        });
        
        
        output.output_file = await report_runs.getOutput_file({
            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.report_definitions,
        as: 'report_definition',
        
        where: filter.report_definition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.report_definition.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.report_definition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'output_file',
      },

    ];

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

            
            if (filter.filters_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'report_runs',
                        'filters_json',
                        filter.filters_json,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'report_runs',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.output_format) {
                where = {
                    ...where,
                output_format: filter.output_format,
            };
            }
            
            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.report_runs.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(
                        'report_runs',
                        'status',
                        query,
                    ),
                ],
            };
        }

        const records = await db.report_runs.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,
        }));
    }

    
};

