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

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

        const refresh_jobs = await db.refresh_jobs.create(
            {
                id: data.id || undefined,
        
        job_type: data.job_type
        ||
        null
            ,
            
        job_status: data.job_status
        ||
        null
            ,
            
        scheduled_for: data.scheduled_for
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        job_summary: data.job_summary
        ||
        null
            ,
            
        job_log: data.job_log
        ||
        null
            ,
            
        approval_required: data.approval_required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await refresh_jobs.setKnowledge_source( data.knowledge_source || null, {
            transaction,
        });
        

        

        

        return refresh_jobs;
    }
    

    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 refresh_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                job_type: item.job_type
            ||
            null
            ,
            
                job_status: item.job_status
            ||
            null
            ,
            
                scheduled_for: item.scheduled_for
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                job_summary: item.job_summary
            ||
            null
            ,
            
                job_log: item.job_log
            ||
            null
            ,
            
                approval_required: item.approval_required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return refresh_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.job_type !== undefined) updatePayload.job_type = data.job_type;
        
        
        if (data.job_status !== undefined) updatePayload.job_status = data.job_status;
        
        
        if (data.scheduled_for !== undefined) updatePayload.scheduled_for = data.scheduled_for;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.job_summary !== undefined) updatePayload.job_summary = data.job_summary;
        
        
        if (data.job_log !== undefined) updatePayload.job_log = data.job_log;
        
        
        if (data.approval_required !== undefined) updatePayload.approval_required = data.approval_required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.knowledge_source !== undefined) {
            await refresh_jobs.setKnowledge_source(
              
              data.knowledge_source,
              
              { transaction }
            );
        }
        

        
        

        

        return refresh_jobs;
    }

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

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

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


        return refresh_jobs;
    }

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

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

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

        await refresh_jobs.destroy({
            transaction
        });

        return refresh_jobs;
    }

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

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

        if (!refresh_jobs) {
            return refresh_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.knowledge_source = await refresh_jobs.getKnowledge_source({
            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.knowledge_sources,
        as: 'knowledge_source',
        
        where: filter.knowledge_source ? {
          [Op.or]: [
            { id: { [Op.in]: filter.knowledge_source.split('|').map(term => Utils.uuid(term)) } },
            {
              source_name: {
                [Op.or]: filter.knowledge_source.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.job_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_jobs',
                        'job_summary',
                        filter.job_summary,
                    ),
                };
            }
            
            if (filter.job_log) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'refresh_jobs',
                        'job_log',
                        filter.job_log,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.job_type) {
                where = {
                    ...where,
                job_type: filter.job_type,
            };
            }
            
            if (filter.job_status) {
                where = {
                    ...where,
                job_status: filter.job_status,
            };
            }
            
            if (filter.approval_required) {
                where = {
                    ...where,
                approval_required: filter.approval_required,
            };
            }
            


      



            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.refresh_jobs.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(
                        'refresh_jobs',
                        'job_summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

