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

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

        const workflow_rules = await db.workflow_rules.create(
            {
                id: data.id || undefined,
        
        l1_threshold_usd: data.l1_threshold_usd
        ||
        null
            ,
            
        l2_threshold_usd: data.l2_threshold_usd
        ||
        null
            ,
            
        l3_threshold_usd: data.l3_threshold_usd
        ||
        null
            ,
            
        l4_threshold_usd: data.l4_threshold_usd
        ||
        null
            ,
            
        sla_approval_hours: data.sla_approval_hours
        ||
        null
            ,
            
        sla_procurement_hours: data.sla_procurement_hours
        ||
        null
            ,
            
        sla_reception_hours: data.sla_reception_hours
        ||
        null
            ,
            
        rate_limit_profile: data.rate_limit_profile
        ||
        null
            ,
            
        require_reject_reason: data.require_reject_reason
        ||
        false
        
            ,
            
        require_return_comment: data.require_return_comment
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return workflow_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 workflow_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                l1_threshold_usd: item.l1_threshold_usd
            ||
            null
            ,
            
                l2_threshold_usd: item.l2_threshold_usd
            ||
            null
            ,
            
                l3_threshold_usd: item.l3_threshold_usd
            ||
            null
            ,
            
                l4_threshold_usd: item.l4_threshold_usd
            ||
            null
            ,
            
                sla_approval_hours: item.sla_approval_hours
            ||
            null
            ,
            
                sla_procurement_hours: item.sla_procurement_hours
            ||
            null
            ,
            
                sla_reception_hours: item.sla_reception_hours
            ||
            null
            ,
            
                rate_limit_profile: item.rate_limit_profile
            ||
            null
            ,
            
                require_reject_reason: item.require_reject_reason
            ||
            false
        
            ,
            
                require_return_comment: item.require_return_comment
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.l1_threshold_usd !== undefined) updatePayload.l1_threshold_usd = data.l1_threshold_usd;
        
        
        if (data.l2_threshold_usd !== undefined) updatePayload.l2_threshold_usd = data.l2_threshold_usd;
        
        
        if (data.l3_threshold_usd !== undefined) updatePayload.l3_threshold_usd = data.l3_threshold_usd;
        
        
        if (data.l4_threshold_usd !== undefined) updatePayload.l4_threshold_usd = data.l4_threshold_usd;
        
        
        if (data.sla_approval_hours !== undefined) updatePayload.sla_approval_hours = data.sla_approval_hours;
        
        
        if (data.sla_procurement_hours !== undefined) updatePayload.sla_procurement_hours = data.sla_procurement_hours;
        
        
        if (data.sla_reception_hours !== undefined) updatePayload.sla_reception_hours = data.sla_reception_hours;
        
        
        if (data.rate_limit_profile !== undefined) updatePayload.rate_limit_profile = data.rate_limit_profile;
        
        
        if (data.require_reject_reason !== undefined) updatePayload.require_reject_reason = data.require_reject_reason;
        
        
        if (data.require_return_comment !== undefined) updatePayload.require_return_comment = data.require_return_comment;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return workflow_rules;
    }

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

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

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


        return workflow_rules;
    }

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

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

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

        await workflow_rules.destroy({
            transaction
        });

        return workflow_rules;
    }

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

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

        if (!workflow_rules) {
            return workflow_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await workflow_rules.getTenant({
            transaction
        });
        
        
        output.organizations = await workflow_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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              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.l1_threshold_usdRange) {
                const [start, end] = filter.l1_threshold_usdRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.rate_limit_profile) {
                where = {
                    ...where,
                rate_limit_profile: filter.rate_limit_profile,
            };
            }
            
            if (filter.require_reject_reason) {
                where = {
                    ...where,
                require_reject_reason: filter.require_reject_reason,
            };
            }
            
            if (filter.require_return_comment) {
                where = {
                    ...where,
                require_return_comment: filter.require_return_comment,
            };
            }
            


      

      
      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.workflow_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(
                        'workflow_rules',
                        'rate_limit_profile',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

