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

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

        const referral_conversions = await db.referral_conversions.create(
            {
                id: data.id || undefined,
        
        converted_at: data.converted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        commission_amount: data.commission_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await referral_conversions.setReferral_link( data.referral_link || null, {
            transaction,
        });
        
        await referral_conversions.setReferred_user( data.referred_user || null, {
            transaction,
        });
        
        await referral_conversions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return referral_conversions;
    }
    

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

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

        // For each item created, replace relation files
        

        return referral_conversions;
    }

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


        

        const updatePayload = {};
        
        if (data.converted_at !== undefined) updatePayload.converted_at = data.converted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.referral_link !== undefined) {
            await referral_conversions.setReferral_link(
              
              data.referral_link,
              
              { transaction }
            );
        }
        
        if (data.referred_user !== undefined) {
            await referral_conversions.setReferred_user(
              
              data.referred_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await referral_conversions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return referral_conversions;
    }

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

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

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


        return referral_conversions;
    }

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

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

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

        await referral_conversions.destroy({
            transaction
        });

        return referral_conversions;
    }

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

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

        if (!referral_conversions) {
            return referral_conversions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.referral_link = await referral_conversions.getReferral_link({
            transaction
        });
        
        
        output.referred_user = await referral_conversions.getReferred_user({
            transaction
        });
        
        
        output.organizations = await referral_conversions.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.referral_links,
        as: 'referral_link',
        
        where: filter.referral_link ? {
          [Op.or]: [
            { id: { [Op.in]: filter.referral_link.split('|').map(term => Utils.uuid(term)) } },
            {
              code: {
                [Op.or]: filter.referral_link.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'referred_user',
        
        where: filter.referred_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.referred_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.referred_user.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.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'referral_conversions',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

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

        const records = await db.referral_conversions.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,
        }));
    }

    
};

