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

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

        const commission_rules = await db.commission_rules.create(
            {
                id: data.id || undefined,
        
        applies_to_role: data.applies_to_role
        ||
        null
            ,
            
        commission_type: data.commission_type
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        min_order_amount: data.min_order_amount
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        rule_name: data.rule_name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await commission_rules.setCommission_plan( data.commission_plan || null, {
            transaction,
        });
        
        await commission_rules.setProduct( data.product || null, {
            transaction,
        });
        
        await commission_rules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return commission_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 commission_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                applies_to_role: item.applies_to_role
            ||
            null
            ,
            
                commission_type: item.commission_type
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                min_order_amount: item.min_order_amount
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                rule_name: item.rule_name
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.applies_to_role !== undefined) updatePayload.applies_to_role = data.applies_to_role;
        
        
        if (data.commission_type !== undefined) updatePayload.commission_type = data.commission_type;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.min_order_amount !== undefined) updatePayload.min_order_amount = data.min_order_amount;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.rule_name !== undefined) updatePayload.rule_name = data.rule_name;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.commission_plan !== undefined) {
            await commission_rules.setCommission_plan(
              
              data.commission_plan,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await commission_rules.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await commission_rules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return commission_rules;
    }

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

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

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


        return commission_rules;
    }

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

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

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

        await commission_rules.destroy({
            transaction
        });

        return commission_rules;
    }

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

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

        if (!commission_rules) {
            return commission_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.commission_plan = await commission_rules.getCommission_plan({
            transaction
        });
        
        
        output.product = await commission_rules.getProduct({
            transaction
        });
        
        
        output.organizations = await commission_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.commission_plans,
        as: 'commission_plan',
        
        where: filter.commission_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.commission_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              plan_name: {
                [Op.or]: filter.commission_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.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.rule_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'commission_rules',
                        'rule_name',
                        filter.rule_name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.applies_to_role) {
                where = {
                    ...where,
                applies_to_role: filter.applies_to_role,
            };
            }
            
            if (filter.commission_type) {
                where = {
                    ...where,
                commission_type: filter.commission_type,
            };
            }
            
            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.commission_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(
                        'commission_rules',
                        'rule_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

