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

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

        const referrals = await db.referrals.create(
            {
                id: data.id || undefined,
        
        referral_code: data.referral_code
        ||
        null
            ,
            
        referred_email: data.referred_email
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        invited_at: data.invited_at
        ||
        null
            ,
            
        signed_up_at: data.signed_up_at
        ||
        null
            ,
            
        rewarded_at: data.rewarded_at
        ||
        null
            ,
            
        reward_doodlecoins: data.reward_doodlecoins
        ||
        null
            ,
            
        note: data.note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await referrals.setReferrer( data.referrer || null, {
            transaction,
        });
        
        await referrals.setReferred_user( data.referred_user || null, {
            transaction,
        });
        

        

        

        return referrals;
    }
    

    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 referralsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                referral_code: item.referral_code
            ||
            null
            ,
            
                referred_email: item.referred_email
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                invited_at: item.invited_at
            ||
            null
            ,
            
                signed_up_at: item.signed_up_at
            ||
            null
            ,
            
                rewarded_at: item.rewarded_at
            ||
            null
            ,
            
                reward_doodlecoins: item.reward_doodlecoins
            ||
            null
            ,
            
                note: item.note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return referrals;
    }

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

        const referrals = await db.referrals.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.referral_code !== undefined) updatePayload.referral_code = data.referral_code;
        
        
        if (data.referred_email !== undefined) updatePayload.referred_email = data.referred_email;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
        
        
        if (data.signed_up_at !== undefined) updatePayload.signed_up_at = data.signed_up_at;
        
        
        if (data.rewarded_at !== undefined) updatePayload.rewarded_at = data.rewarded_at;
        
        
        if (data.reward_doodlecoins !== undefined) updatePayload.reward_doodlecoins = data.reward_doodlecoins;
        
        
        if (data.note !== undefined) updatePayload.note = data.note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.referrer !== undefined) {
            await referrals.setReferrer(
              
              data.referrer,
              
              { transaction }
            );
        }
        
        if (data.referred_user !== undefined) {
            await referrals.setReferred_user(
              
              data.referred_user,
              
              { transaction }
            );
        }
        

        
        

        

        return referrals;
    }

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

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

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


        return referrals;
    }

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

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

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

        await referrals.destroy({
            transaction
        });

        return referrals;
    }

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

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

        if (!referrals) {
            return referrals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.referrer = await referrals.getReferrer({
            transaction
        });
        
        
        output.referred_user = await referrals.getReferred_user({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



    ];

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

            
            if (filter.referral_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'referrals',
                        'referral_code',
                        filter.referral_code,
                    ),
                };
            }
            
            if (filter.referred_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'referrals',
                        'referred_email',
                        filter.referred_email,
                    ),
                };
            }
            
            if (filter.note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'referrals',
                        'note',
                        filter.note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

        

        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.referrals.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'referrals',
                        'referral_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

