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

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

        const commissions = await db.commissions.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        gross_profit_amount: data.gross_profit_amount
        ||
        null
            ,
            
        commission_amount: data.commission_amount
        ||
        null
            ,
            
        commission_rate_percent: data.commission_rate_percent
        ||
        null
            ,
            
        earned_at: data.earned_at
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await commissions.setMembership( data.membership || null, {
            transaction,
        });
        
        await commissions.setOrder( data.order || null, {
            transaction,
        });
        
        await commissions.setWallet_transaction( data.wallet_transaction || null, {
            transaction,
        });
        
        await commissions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return commissions;
    }
    

    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 commissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                gross_profit_amount: item.gross_profit_amount
            ||
            null
            ,
            
                commission_amount: item.commission_amount
            ||
            null
            ,
            
                commission_rate_percent: item.commission_rate_percent
            ||
            null
            ,
            
                earned_at: item.earned_at
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return commissions;
    }

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.gross_profit_amount !== undefined) updatePayload.gross_profit_amount = data.gross_profit_amount;
        
        
        if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
        
        
        if (data.commission_rate_percent !== undefined) updatePayload.commission_rate_percent = data.commission_rate_percent;
        
        
        if (data.earned_at !== undefined) updatePayload.earned_at = data.earned_at;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.membership !== undefined) {
            await commissions.setMembership(
              
              data.membership,
              
              { transaction }
            );
        }
        
        if (data.order !== undefined) {
            await commissions.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        
        if (data.wallet_transaction !== undefined) {
            await commissions.setWallet_transaction(
              
              data.wallet_transaction,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await commissions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return commissions;
    }

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

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

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


        return commissions;
    }

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

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

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

        await commissions.destroy({
            transaction
        });

        return commissions;
    }

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

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

        if (!commissions) {
            return commissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.membership = await commissions.getMembership({
            transaction
        });
        
        
        output.order = await commissions.getOrder({
            transaction
        });
        
        
        output.wallet_transaction = await commissions.getWallet_transaction({
            transaction
        });
        
        
        output.organizations = await commissions.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.affiliate_memberships,
        as: 'membership',
        
        where: filter.membership ? {
          [Op.or]: [
            { id: { [Op.in]: filter.membership.split('|').map(term => Utils.uuid(term)) } },
            {
              referral_code: {
                [Op.or]: filter.membership.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.wallet_transactions,
        as: 'wallet_transaction',
        
        where: filter.wallet_transaction ? {
          [Op.or]: [
            { id: { [Op.in]: filter.wallet_transaction.split('|').map(term => Utils.uuid(term)) } },
            {
              reference_code: {
                [Op.or]: filter.wallet_transaction.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.gross_profit_amountRange) {
                const [start, end] = filter.gross_profit_amountRange;

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    paid_at: {
                    ...where.paid_at,
                            [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.commissions.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(
                        'commissions',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

