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

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

        const request_queue = await db.request_queue.create(
            {
                id: data.id || undefined,
        
        request_id: data.request_id
        ||
        null
            ,
            
        payload: data.payload
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        attempts: data.attempts
        ||
        null
            ,
            
        next_retry: data.next_retry
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await request_queue.setSession( data.session || null, {
            transaction,
        });
        

        

        

        return request_queue;
    }
    

    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 request_queueData = data.map((item, index) => ({
                id: item.id || undefined,
                
                request_id: item.request_id
            ||
            null
            ,
            
                payload: item.payload
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                attempts: item.attempts
            ||
            null
            ,
            
                next_retry: item.next_retry
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return request_queue;
    }

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

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


        

        const updatePayload = {};
        
        if (data.request_id !== undefined) updatePayload.request_id = data.request_id;
        
        
        if (data.payload !== undefined) updatePayload.payload = data.payload;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.attempts !== undefined) updatePayload.attempts = data.attempts;
        
        
        if (data.next_retry !== undefined) updatePayload.next_retry = data.next_retry;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.session !== undefined) {
            await request_queue.setSession(
              
              data.session,
              
              { transaction }
            );
        }
        

        
        

        

        return request_queue;
    }

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

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

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


        return request_queue;
    }

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

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

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

        await request_queue.destroy({
            transaction
        });

        return request_queue;
    }

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

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

        if (!request_queue) {
            return request_queue;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.session = await request_queue.getSession({
            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.fill_sessions,
        as: 'session',
        
        where: filter.session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.session.split('|').map(term => Utils.uuid(term)) } },
            {
              session_name: {
                [Op.or]: filter.session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.request_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'request_queue',
                        'request_id',
                        filter.request_id,
                    ),
                };
            }
            
            if (filter.payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'request_queue',
                        'payload',
                        filter.payload,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    next_retry: {
                    ...where.next_retry,
                            [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.request_queue.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(
                        'request_queue',
                        'request_id',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

