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

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

        const mapping_rules = await db.mapping_rules.create(
            {
                id: data.id || undefined,
        
        source_column: data.source_column
        ||
        null
            ,
            
        target_field: data.target_field
        ||
        null
            ,
            
        transform_type: data.transform_type
        ||
        null
            ,
            
        transform_config: data.transform_config
        ||
        null
            ,
            
        is_required: data.is_required
        ||
        false
        
            ,
            
        order_index: data.order_index
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await mapping_rules.setMapping( data.mapping || null, {
            transaction,
        });
        
        await mapping_rules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return mapping_rules;
    }
    

    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 mapping_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source_column: item.source_column
            ||
            null
            ,
            
                target_field: item.target_field
            ||
            null
            ,
            
                transform_type: item.transform_type
            ||
            null
            ,
            
                transform_config: item.transform_config
            ||
            null
            ,
            
                is_required: item.is_required
            ||
            false
        
            ,
            
                order_index: item.order_index
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return mapping_rules;
    }

    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 mapping_rules = await db.mapping_rules.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.source_column !== undefined) updatePayload.source_column = data.source_column;
        
        
        if (data.target_field !== undefined) updatePayload.target_field = data.target_field;
        
        
        if (data.transform_type !== undefined) updatePayload.transform_type = data.transform_type;
        
        
        if (data.transform_config !== undefined) updatePayload.transform_config = data.transform_config;
        
        
        if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
        
        
        if (data.order_index !== undefined) updatePayload.order_index = data.order_index;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.mapping !== undefined) {
            await mapping_rules.setMapping(
              
              data.mapping,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await mapping_rules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return mapping_rules;
    }

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

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

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


        return mapping_rules;
    }

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

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

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

        await mapping_rules.destroy({
            transaction
        });

        return mapping_rules;
    }

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

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

        if (!mapping_rules) {
            return mapping_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mapping = await mapping_rules.getMapping({
            transaction
        });
        
        
        output.organizations = await mapping_rules.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_mappings,
        as: 'mapping',
        
        where: filter.mapping ? {
          [Op.or]: [
            { id: { [Op.in]: filter.mapping.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.mapping.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.source_column) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mapping_rules',
                        'source_column',
                        filter.source_column,
                    ),
                };
            }
            
            if (filter.target_field) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mapping_rules',
                        'target_field',
                        filter.target_field,
                    ),
                };
            }
            
            if (filter.transform_config) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'mapping_rules',
                        'transform_config',
                        filter.transform_config,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.transform_type) {
                where = {
                    ...where,
                transform_type: filter.transform_type,
            };
            }
            
            if (filter.is_required) {
                where = {
                    ...where,
                is_required: filter.is_required,
            };
            }
            


      

      
      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.mapping_rules.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(
                        'mapping_rules',
                        'target_field',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

