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

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

        const demo_wallets = await db.demo_wallets.create(
            {
                id: data.id || undefined,
        
        available_balance: data.available_balance
        ||
        null
            ,
            
        lifetime_earned: data.lifetime_earned
        ||
        null
            ,
            
        lifetime_spent: data.lifetime_spent
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        payouts_enabled: data.payouts_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await demo_wallets.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await demo_wallets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return demo_wallets;
    }
    

    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 demo_walletsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                available_balance: item.available_balance
            ||
            null
            ,
            
                lifetime_earned: item.lifetime_earned
            ||
            null
            ,
            
                lifetime_spent: item.lifetime_spent
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                payouts_enabled: item.payouts_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return demo_wallets;
    }

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


        

        const updatePayload = {};
        
        if (data.available_balance !== undefined) updatePayload.available_balance = data.available_balance;
        
        
        if (data.lifetime_earned !== undefined) updatePayload.lifetime_earned = data.lifetime_earned;
        
        
        if (data.lifetime_spent !== undefined) updatePayload.lifetime_spent = data.lifetime_spent;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.payouts_enabled !== undefined) updatePayload.payouts_enabled = data.payouts_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_user !== undefined) {
            await demo_wallets.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await demo_wallets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return demo_wallets;
    }

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

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

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


        return demo_wallets;
    }

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

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

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

        await demo_wallets.destroy({
            transaction
        });

        return demo_wallets;
    }

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

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

        if (!demo_wallets) {
            return demo_wallets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.wallet_transactions_wallet = await demo_wallets.getWallet_transactions_wallet({
            transaction
        });
        
        
        
        output.owner_user = await demo_wallets.getOwner_user({
            transaction
        });
        
        
        output.organizations = await demo_wallets.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.users,
        as: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_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(
                        'demo_wallets',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.payouts_enabled) {
                where = {
                    ...where,
                payouts_enabled: filter.payouts_enabled,
            };
            }
            


      

      
      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.demo_wallets.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(
                        'demo_wallets',
                        'currency',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

