
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,
        
        commission_code: data.commission_code
        ||
        null
            ,
            
        commission_status: data.commission_status
        ||
        null
            ,
            
        commission_type: data.commission_type
        ||
        null
            ,
            
        base_amount: data.base_amount
        ||
        null
            ,
            
        commission_amount: data.commission_amount
        ||
        null
            ,
            
        earned_at: data.earned_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await commissions.setTenant( data.tenant || null, {
            transaction,
        });
        
        await commissions.setOrder( data.order || null, {
            transaction,
        });
        
        await commissions.setOrder_item( data.order_item || null, {
            transaction,
        });
        
        await commissions.setBeneficiary_user( data.beneficiary_user || null, {
            transaction,
        });
        
        await commissions.setCommission_plan( data.commission_plan || 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,
                
                commission_code: item.commission_code
            ||
            null
            ,
            
                commission_status: item.commission_status
            ||
            null
            ,
            
                commission_type: item.commission_type
            ||
            null
            ,
            
                base_amount: item.base_amount
            ||
            null
            ,
            
                commission_amount: item.commission_amount
            ||
            null
            ,
            
                earned_at: item.earned_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            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.commission_code !== undefined) updatePayload.commission_code = data.commission_code;
        
        
        if (data.commission_status !== undefined) updatePayload.commission_status = data.commission_status;
        
        
        if (data.commission_type !== undefined) updatePayload.commission_type = data.commission_type;
        
        
        if (data.base_amount !== undefined) updatePayload.base_amount = data.base_amount;
        
        
        if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
        
        
        if (data.earned_at !== undefined) updatePayload.earned_at = data.earned_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await commissions.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.order !== undefined) {
            await commissions.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        
        if (data.order_item !== undefined) {
            await commissions.setOrder_item(
              
              data.order_item,
              
              { transaction }
            );
        }
        
        if (data.beneficiary_user !== undefined) {
            await commissions.setBeneficiary_user(
              
              data.beneficiary_user,
              
              { transaction }
            );
        }
        
        if (data.commission_plan !== undefined) {
            await commissions.setCommission_plan(
              
              data.commission_plan,
              
              { 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.tenant = await commissions.getTenant({
            transaction
        });
        
        
        output.order = await commissions.getOrder({
            transaction
        });
        
        
        output.order_item = await commissions.getOrder_item({
            transaction
        });
        
        
        output.beneficiary_user = await commissions.getBeneficiary_user({
            transaction
        });
        
        
        output.commission_plan = await commissions.getCommission_plan({
            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.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.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.order_items,
        as: 'order_item',
        
        where: filter.order_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.order_item.split('|').map(term => Utils.uuid(term)) } },
            {
              item_name: {
                [Op.or]: filter.order_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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.organizations,
        as: 'organizations',
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.commission_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'commissions',
                        'commission_code',
                        filter.commission_code,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'commissions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    base_amount: {
                    ...where.base_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.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.approved_atRange) {
                const [start, end] = filter.approved_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    approved_at: {
                    ...where.approved_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.commission_status) {
                where = {
                    ...where,
                commission_status: filter.commission_status,
            };
            }
            
            if (filter.commission_type) {
                where = {
                    ...where,
                commission_type: filter.commission_type,
            };
            }
            


      

      

      

      

      

      
      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',
                        'commission_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

