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

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

        const data_export_jobs = await db.data_export_jobs.create(
            {
                id: data.id || undefined,
        
        export_type: data.export_type
        ||
        null
            ,
            
        source_connection_name: data.source_connection_name
        ||
        null
            ,
            
        target_connection_name: data.target_connection_name
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await data_export_jobs.setBusiness( data.business || null, {
            transaction,
        });
        
        await data_export_jobs.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        

        

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

        return data_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 data_export_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                export_type: item.export_type
            ||
            null
            ,
            
                source_connection_name: item.source_connection_name
            ||
            null
            ,
            
                target_connection_name: item.target_connection_name
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            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 data_export_jobs = await db.data_export_jobs.bulkCreate(data_export_jobsData, { transaction });

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

        return data_export_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.export_type !== undefined) updatePayload.export_type = data.export_type;
        
        
        if (data.source_connection_name !== undefined) updatePayload.source_connection_name = data.source_connection_name;
        
        
        if (data.target_connection_name !== undefined) updatePayload.target_connection_name = data.target_connection_name;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.business !== undefined) {
            await data_export_jobs.setBusiness(
              
              data.business,
              
              { transaction }
            );
        }
        
        if (data.requested_by_user !== undefined) {
            await data_export_jobs.setRequested_by_user(
              
              data.requested_by_user,
              
              { transaction }
            );
        }
        

        
        

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

        return data_export_jobs;
    }

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

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

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


        return data_export_jobs;
    }

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

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

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

        await data_export_jobs.destroy({
            transaction
        });

        return data_export_jobs;
    }

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

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

        if (!data_export_jobs) {
            return data_export_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.business = await data_export_jobs.getBusiness({
            transaction
        });
        
        
        output.requested_by_user = await data_export_jobs.getRequested_by_user({
            transaction
        });
        
        
        output.log_file = await data_export_jobs.getLog_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.businesses,
        as: 'business',
        
        where: filter.business ? {
          [Op.or]: [
            { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.business.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: 'log_file',
      },

    ];

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

            
            if (filter.source_connection_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_export_jobs',
                        'source_connection_name',
                        filter.source_connection_name,
                    ),
                };
            }
            
            if (filter.target_connection_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_export_jobs',
                        'target_connection_name',
                        filter.target_connection_name,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'data_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.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.data_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(
                        'data_export_jobs',
                        'export_type',
                        query,
                    ),
                ],
            };
        }

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

    
};

