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

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

        const helcim_configurations = await db.helcim_configurations.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        api_token_label: data.api_token_label
        ||
        null
            ,
            
        enable_revenue_sharing: data.enable_revenue_sharing
        ||
        false
        
            ,
            
        platform_fee_percent: data.platform_fee_percent
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await helcim_configurations.setTenant( data.tenant || null, {
            transaction,
        });
        
        await helcim_configurations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return helcim_configurations;
    }
    

    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 helcim_configurationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                api_token_label: item.api_token_label
            ||
            null
            ,
            
                enable_revenue_sharing: item.enable_revenue_sharing
            ||
            false
        
            ,
            
                platform_fee_percent: item.platform_fee_percent
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return helcim_configurations;
    }

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


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.api_token_label !== undefined) updatePayload.api_token_label = data.api_token_label;
        
        
        if (data.enable_revenue_sharing !== undefined) updatePayload.enable_revenue_sharing = data.enable_revenue_sharing;
        
        
        if (data.platform_fee_percent !== undefined) updatePayload.platform_fee_percent = data.platform_fee_percent;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await helcim_configurations.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await helcim_configurations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return helcim_configurations;
    }

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

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

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


        return helcim_configurations;
    }

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

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

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

        await helcim_configurations.destroy({
            transaction
        });

        return helcim_configurations;
    }

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

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

        if (!helcim_configurations) {
            return helcim_configurations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await helcim_configurations.getTenant({
            transaction
        });
        
        
        output.organizations = await helcim_configurations.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.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.api_token_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'helcim_configurations',
                        'api_token_label',
                        filter.api_token_label,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.environment) {
                where = {
                    ...where,
                environment: filter.environment,
            };
            }
            
            if (filter.enable_revenue_sharing) {
                where = {
                    ...where,
                enable_revenue_sharing: filter.enable_revenue_sharing,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

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

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

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

    
};

