
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,
        
        status: data.status
        ||
        null
            ,
            
        original_filename: data.original_filename
        ||
        null
            ,
            
        mapping_json: data.mapping_json
        ||
        null
            ,
            
        total_rows: data.total_rows
        ||
        null
            ,
            
        imported_rows: data.imported_rows
        ||
        null
            ,
            
        failed_rows: data.failed_rows
        ||
        null
            ,
            
        error_summary: data.error_summary
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await csv_import_jobs.setTrading_account( data.trading_account || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.csv_import_jobs.getTableName(),
                belongsToColumn: 'source_file',
                belongsToId: csv_import_jobs.id,
            },
            data.source_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,
                
                status: item.status
            ||
            null
            ,
            
                original_filename: item.original_filename
            ||
            null
            ,
            
                mapping_json: item.mapping_json
            ||
            null
            ,
            
                total_rows: item.total_rows
            ||
            null
            ,
            
                imported_rows: item.imported_rows
            ||
            null
            ,
            
                failed_rows: item.failed_rows
            ||
            null
            ,
            
                error_summary: item.error_summary
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            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: 'source_file',
                    belongsToId: csv_import_jobs[i].id,
                },
                data[i].source_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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.original_filename !== undefined) updatePayload.original_filename = data.original_filename;
        
        
        if (data.mapping_json !== undefined) updatePayload.mapping_json = data.mapping_json;
        
        
        if (data.total_rows !== undefined) updatePayload.total_rows = data.total_rows;
        
        
        if (data.imported_rows !== undefined) updatePayload.imported_rows = data.imported_rows;
        
        
        if (data.failed_rows !== undefined) updatePayload.failed_rows = data.failed_rows;
        
        
        if (data.error_summary !== undefined) updatePayload.error_summary = data.error_summary;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trading_account !== undefined) {
            await csv_import_jobs.setTrading_account(
              
              data.trading_account,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.csv_import_jobs.getTableName(),
                belongsToColumn: 'source_file',
                belongsToId: csv_import_jobs.id,
            },
            data.source_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.csv_import_row_errors_csv_import_job = await csv_import_jobs.getCsv_import_row_errors_csv_import_job({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.trading_account = await csv_import_jobs.getTrading_account({
            transaction
        });
        
        
        output.source_file = await csv_import_jobs.getSource_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.trading_accounts,
        as: 'trading_account',
        
        where: filter.trading_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trading_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trading_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'source_file',
      },

    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

    
};

