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

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

        const import_row_results = await db.import_row_results.create(
            {
                id: data.id || undefined,
        
        row_number: data.row_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        raw_row: data.raw_row
        ||
        null
            ,
            
        normalized_row: data.normalized_row
        ||
        null
            ,
            
        primary_key_hint: data.primary_key_hint
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await import_row_results.setImport_job( data.import_job || null, {
            transaction,
        });
        
        await import_row_results.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return import_row_results;
    }
    

    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 import_row_resultsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                row_number: item.row_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                raw_row: item.raw_row
            ||
            null
            ,
            
                normalized_row: item.normalized_row
            ||
            null
            ,
            
                primary_key_hint: item.primary_key_hint
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return import_row_results;
    }

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

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


        

        const updatePayload = {};
        
        if (data.row_number !== undefined) updatePayload.row_number = data.row_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.raw_row !== undefined) updatePayload.raw_row = data.raw_row;
        
        
        if (data.normalized_row !== undefined) updatePayload.normalized_row = data.normalized_row;
        
        
        if (data.primary_key_hint !== undefined) updatePayload.primary_key_hint = data.primary_key_hint;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.import_job !== undefined) {
            await import_row_results.setImport_job(
              
              data.import_job,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await import_row_results.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return import_row_results;
    }

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

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

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


        return import_row_results;
    }

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

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

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

        await import_row_results.destroy({
            transaction
        });

        return import_row_results;
    }

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

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

        if (!import_row_results) {
            return import_row_results;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.import_issues_row_result = await import_row_results.getImport_issues_row_result({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.import_job = await import_row_results.getImport_job({
            transaction
        });
        
        
        output.organizations = await import_row_results.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.import_jobs,
        as: 'import_job',
        
        where: filter.import_job ? {
          [Op.or]: [
            { id: { [Op.in]: filter.import_job.split('|').map(term => Utils.uuid(term)) } },
            {
              job_name: {
                [Op.or]: filter.import_job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.raw_row) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'import_row_results',
                        'raw_row',
                        filter.raw_row,
                    ),
                };
            }
            
            if (filter.normalized_row) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'import_row_results',
                        'normalized_row',
                        filter.normalized_row,
                    ),
                };
            }
            
            if (filter.primary_key_hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'import_row_results',
                        'primary_key_hint',
                        filter.primary_key_hint,
                    ),
                };
            }
            

            
            

            
            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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.import_row_results.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'import_row_results',
                        'primary_key_hint',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

