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

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

        const screener_runs = await db.screener_runs.create(
            {
                id: data.id || undefined,
        
        run_at: data.run_at
        ||
        null
            ,
            
        result_count: data.result_count
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await screener_runs.setScreener_filter( data.screener_filter || null, {
            transaction,
        });
        

        

        

        return screener_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 screener_runsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                run_at: item.run_at
            ||
            null
            ,
            
                result_count: item.result_count
            ||
            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 screener_runs = await db.screener_runs.bulkCreate(screener_runsData, { transaction });

        // For each item created, replace relation files
        

        return screener_runs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.run_at !== undefined) updatePayload.run_at = data.run_at;
        
        
        if (data.result_count !== undefined) updatePayload.result_count = data.result_count;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.screener_filter !== undefined) {
            await screener_runs.setScreener_filter(
              
              data.screener_filter,
              
              { transaction }
            );
        }
        

        
        

        

        return screener_runs;
    }

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

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

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


        return screener_runs;
    }

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

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

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

        await screener_runs.destroy({
            transaction
        });

        return screener_runs;
    }

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

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

        if (!screener_runs) {
            return screener_runs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.screener_results_screener_run = await screener_runs.getScreener_results_screener_run({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.screener_filter = await screener_runs.getScreener_filter({
            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.screener_filters,
        as: 'screener_filter',
        
        where: filter.screener_filter ? {
          [Op.or]: [
            { id: { [Op.in]: filter.screener_filter.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.screener_filter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

    
};

