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

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

        const csv_import_jobs = await db.csv_import_jobs.create(
            {
                id: data.id || undefined,
        
        import_entity: data.import_entity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        records_processed: data.records_processed
        ||
        null
            ,
            
        records_failed: data.records_failed
        ||
        null
            ,
            
        error_log: data.error_log
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await csv_import_jobs.setRequested_by_user( data.requested_by_user || null, {
            transaction,
        });
        

        

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

        return csv_import_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 csv_import_jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                import_entity: item.import_entity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                records_processed: item.records_processed
            ||
            null
            ,
            
                records_failed: item.records_failed
            ||
            null
            ,
            
                error_log: item.error_log
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return csv_import_jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.import_entity !== undefined) updatePayload.import_entity = data.import_entity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.records_processed !== undefined) updatePayload.records_processed = data.records_processed;
        
        
        if (data.records_failed !== undefined) updatePayload.records_failed = data.records_failed;
        
        
        if (data.error_log !== undefined) updatePayload.error_log = data.error_log;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return csv_import_jobs;
    }

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

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

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


        return csv_import_jobs;
    }

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

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

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

        await csv_import_jobs.destroy({
            transaction
        });

        return csv_import_jobs;
    }

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

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

        if (!csv_import_jobs) {
            return csv_import_jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by_user = await csv_import_jobs.getRequested_by_user({
            transaction
        });
        
        
        output.csv_file = await csv_import_jobs.getCsv_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.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: 'csv_file',
      },

    ];

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

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

            
            

            
            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.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.records_processedRange) {
                const [start, end] = filter.records_processedRange;

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

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

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

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

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

            
            if (filter.import_entity) {
                where = {
                    ...where,
                import_entity: filter.import_entity,
            };
            }
            
            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.csv_import_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(
                        'csv_import_jobs',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

    
};

