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

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

        const csv_import_row_errors = await db.csv_import_row_errors.create(
            {
                id: data.id || undefined,
        
        row_number: data.row_number
        ||
        null
            ,
            
        raw_row_json: data.raw_row_json
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await csv_import_row_errors.setCsv_import_job( data.csv_import_job || null, {
            transaction,
        });
        

        

        

        return csv_import_row_errors;
    }
    

    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_row_errorsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                row_number: item.row_number
            ||
            null
            ,
            
                raw_row_json: item.raw_row_json
            ||
            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 csv_import_row_errors = await db.csv_import_row_errors.bulkCreate(csv_import_row_errorsData, { transaction });

        // For each item created, replace relation files
        

        return csv_import_row_errors;
    }

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

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


        

        const updatePayload = {};
        
        if (data.row_number !== undefined) updatePayload.row_number = data.row_number;
        
        
        if (data.raw_row_json !== undefined) updatePayload.raw_row_json = data.raw_row_json;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.csv_import_job !== undefined) {
            await csv_import_row_errors.setCsv_import_job(
              
              data.csv_import_job,
              
              { transaction }
            );
        }
        

        
        

        

        return csv_import_row_errors;
    }

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

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

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


        return csv_import_row_errors;
    }

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

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

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

        await csv_import_row_errors.destroy({
            transaction
        });

        return csv_import_row_errors;
    }

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

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

        if (!csv_import_row_errors) {
            return csv_import_row_errors;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.csv_import_job = await csv_import_row_errors.getCsv_import_job({
            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.csv_import_jobs,
        as: 'csv_import_job',
        
        where: filter.csv_import_job ? {
          [Op.or]: [
            { id: { [Op.in]: filter.csv_import_job.split('|').map(term => Utils.uuid(term)) } },
            {
              original_filename: {
                [Op.or]: filter.csv_import_job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.raw_row_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'csv_import_row_errors',
                        'raw_row_json',
                        filter.raw_row_json,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'csv_import_row_errors',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      



            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_row_errors.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_row_errors',
                        'error_message',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

