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

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

        const export_jobs = await db.export_jobs.create(
            {
                id: data.id || undefined,
        
        export_type: data.export_type
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        range_start: data.range_start
        ||
        null
            ,
            
        range_end: data.range_end
        ||
        null
            ,
            
        included_sections: data.included_sections
        ||
        null
            ,
            
        chief_complaint: data.chief_complaint
        ||
        null
            ,
            
        questions_for_doctor: data.questions_for_doctor
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await export_jobs.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return export_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 export_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                export_type: item.export_type
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                range_start: item.range_start
            ||
            null
            ,
            
                range_end: item.range_end
            ||
            null
            ,
            
                included_sections: item.included_sections
            ||
            null
            ,
            
                chief_complaint: item.chief_complaint
            ||
            null
            ,
            
                questions_for_doctor: item.questions_for_doctor
            ||
            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 export_jobs = await db.export_jobs.bulkCreate(export_jobsData, { transaction });

        // For each item created, replace relation files
        

        return export_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.export_type !== undefined) updatePayload.export_type = data.export_type;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.range_start !== undefined) updatePayload.range_start = data.range_start;
        
        
        if (data.range_end !== undefined) updatePayload.range_end = data.range_end;
        
        
        if (data.included_sections !== undefined) updatePayload.included_sections = data.included_sections;
        
        
        if (data.chief_complaint !== undefined) updatePayload.chief_complaint = data.chief_complaint;
        
        
        if (data.questions_for_doctor !== undefined) updatePayload.questions_for_doctor = data.questions_for_doctor;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await export_jobs.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return export_jobs;
    }

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

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

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


        return export_jobs;
    }

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

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

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

        await export_jobs.destroy({
            transaction
        });

        return export_jobs;
    }

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

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

        if (!export_jobs) {
            return export_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await export_jobs.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.included_sections) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_jobs',
                        'included_sections',
                        filter.included_sections,
                    ),
                };
            }
            
            if (filter.chief_complaint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_jobs',
                        'chief_complaint',
                        filter.chief_complaint,
                    ),
                };
            }
            
            if (filter.questions_for_doctor) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_jobs',
                        'questions_for_doctor',
                        filter.questions_for_doctor,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_jobs',
                        '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.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

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

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

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

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

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

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

            
            if (filter.export_type) {
                where = {
                    ...where,
                export_type: filter.export_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.export_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(
                        'export_jobs',
                        'export_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

